Given an array with positive and negative integers. Re-range it to interleaving with positive and negative integers. Note You are not necessary to keep the original order or positive integers or negative integers. Example Given [-1, -2, -3, 4, 5, 6], after re-range, it will be [-1, 5, -2, 4, -3, 6] or any other legal answer. Challenge Do it in-place and without extra memory.
这道题没有给出正数、负数谁多谁少,所以需要先统计数量,数量多的要包着数量少的,然后数组尾部全是数量多的数
1 class Solution { 2 /** 3 * @param A: An integer array. 4 * @return an integer array 5 */ 6 public int[] rerange(int[] A) { 7 // write your code here 8 int posNum = 0, negNum = 0; 9 for (int elem : A) { 10 if (elem < 0) { 11 negNum++; 12 } 13 else { 14 posNum++; 15 } 16 } 17 int posInd = 1, negInd = 0; 18 if (posNum > negNum) { 19 negInd = 1; 20 posInd = 0; 21 } 22 while (posInd<A.length && negInd<A.length) { 23 while (posInd < A.length && A[posInd] > 0) { 24 posInd += 2; 25 } 26 while (negInd < A.length && A[negInd] < 0) { 27 negInd += 2; 28 } 29 if (posInd<A.length && negInd<A.length) { 30 swap(A, posInd, negInd);
33 } 34 } 35 return A; 36 } 37 38 public void swap(int[] A, int l, int r) { 39 int temp = A[l]; 40 A[l] = A[r]; 41 A[r] = temp; 42 } 43 }