Interleaving Positive and Negative Numbers(交错正负数)

http://www.lintcode.com/zh-cn/problem/interleaving-positive-and-negative-numbers/

public class Solution {
    /*
     * @param A: An integer array.
     * @return: nothing
     */
     public void rerange(int[] A) {
        // write your code here
        Arrays.sort(A);
        int l = 0, r = A.length - 1;
        if (A.length % 2 == 0) {
            //正负数数量相等。负数可以在前边,但要正数结尾
            l++;
            r--;
        } else if (A[(A.length - 1) >>> 1] > 0) {
            //正数多,正数要打头还要结尾
            r--;
        } else {
            //负数多,负数要打头还要结尾
            l++;
        }
        while (l < r) {
            swap(l, r, A);
            l += 2;
            r -= 2;

        }
    }

    private void swap(int l, int r, int[] a) {
        int temp = a[l];
        a[l] = a[r];
        a[r] = temp;
    }
}

你可能感兴趣的:(Interleaving Positive and Negative Numbers(交错正负数))