Untitled

 avatar
unknown
plain_text
9 months ago
2.2 kB
11
Indexable
package ARRAYS;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class RearrangeArr {

    /**
     *
     * This class takes an integer array nums of even length consisting of an equal number of positive and negative integers.Return the answer array in such a way that the given conditions are met
     * Every consecutive pair of integers have opposite signs.
     * For all integers with the same sign, the order in which they were present in nums is preserved.
     * The rearranged array begins with a positive integer.
     *
     * Examples:
     * Input : nums = [2, 4, 5, -1, -3, -4]
     * Output : [2, -1, 4, -3, 5, -4]
     * Explanation:
     * The positive number 2, 4, 5 maintain their relative positions and -1, -3, -4 maintain their relative positions

     * Input : nums = [1, -1, -3, -4, 2, 3]
     * Output : [1, -1, 2, -3, 3, -4]
     * Explanation:
     * The positive number 1, 2, 3 maintain their relative positions and -1, -3, -4 maintain their relative positions
     */

    public static int[] rearrangeArr(int[] nums){

        List<Integer> negNums = new ArrayList<>();
        List<Integer> posNums = new ArrayList<>();
        int[] resArr = new int[nums.length];

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                posNums.add(nums[i]);
            } else {
                negNums.add(nums[i]);
            }
        }

        int posIndex = 0;
        int negIndex = 0;

        for (int i = 0; i < nums.length; i++) {
            if (i % 2 == 0) {
                resArr[i] = posNums.get(posIndex++);
            } else {
                resArr[i] = negNums.get(negIndex++);
            }
        }
        return resArr;
    }

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        System.out.print(" ENTER ARRYA SIZE -> ");
        int size = s.nextInt();
        int arr[] = new int[size];

        System.out.println("ENTER ARRAY ELEMENTS -> ");
        for (int i = 0; i < size; i++) {
            arr[i] = s.nextInt();
        }
        System.out.println("ORDER -> " + Arrays.toString(rearrangeArr(arr)));
    }
}
Editor is loading...
Leave a Comment