Rearrange array in alternating positive & negative items with O(1) extra space Given an array of positive and negative numbers, arrange them in an alternate fashion such that every positive number is followed by negative and vice-versa maintaining the order of appearance. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in the end of the array.

Example:

Input: arr[] = {1, 2, 3, -4, -1, 4} Output: arr[] = {-4, 1, -1, 2, 3, 4}

Input: arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8} output: arr[] = {-5, 5, -2, 2, -8, 4, 7, 1, 8, 0} The idea is to process array from left to right. While processing, find the first out of place element in the remaining unprocessed array. An element is out of place if it is negative and at odd index, or it is positive and at even index. Once we find an out of place element, we find the first element after it with opposite sign. We right rotate the subarray between these two elements (including these two). 这个题如果用O(n)的space那就很直接,如果用O(1)的话那需要有一个pointer指向第一个错误的数字,比如偶数index的正数和奇数index的负数。然后碰到当前的数如果符号和错误的那个数不一样,那就rotate那段sub array。

public static int[] rearrangeArray(int[] A) {
    int wrong = -1;
    for (int i = 0; i < A.length; i++) {
        if (wrong == -1) {
            if (i % 2 == 0 && A[i] > 0 || i % 2 != 0 && A[i] < 0)
                wrong = i;
        } else {
            if (A[wrong]>= 0 && A[i] < 0 || A[wrong] < 0 && A[i] >= 0) {
                rotate(A, wrong, i);
                if (i - wrong >= 2)
                    wrong = wrong + 2;// if -1 -1 4 ->4 -1 -1 wrong should poing to -1
                else
                    wrong = -1; // if 4 -1 ->-1 4 (no wrong in between)
            }
        }
    }
    return A;
}
 //right rotate wrong ~ current, shif all items right by 1 pos and move current to left most pos(original wrong pos).
public static void rotate(int[] A, int wrong, int current) {
    int temp = A[current];
    for (int i = current; i > wrong; i--)
        A[i] = A[i-1];
    A<div class="answer"></div> = temp;
}

ref:

results matching ""

    No results matching ""