Interleaving Positive and Negative Numbers(交錯正負数)

850 ワード

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;
    }
}