LintCode144 Interleaving Positive and Negative Numbers
阿新 • • 發佈:2018-12-10
- Interleaving Positive and Negative Numbers
Given an array with positive and negative integers. Re-range it to interleaving with positive and 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 reasonable answer.
Challenge
Do it in-place and without extra memory.
Notice
You are not necessary to keep the original order of positive integers or negative integers.
public void rerange(int[] A) { // write your code here int l = 0, r = A.length - 1; while(l < r){ while(l < r && A[l] < 0){ l++; } while(l < r && A[r] > 0){ r--; } if(l < r){ int temp = A[l]; A[l] = A[r]; A[r] = temp; l++; r--; } } if(l > A.length - l){ //根據正負數多少來交叉,能交叉,則正負數個數最多相差1 interleave(A,1,A.length - 1); }else if(l < A.length - l){ interleave(A,0,A.length - 2); } else{ interleave(A,0,A.length - 1); } } public void interleave(int[] A, int start, int end){ while(start <= end){ int temp = A[start]; A[start] = A[end]; A[end] = temp; start += 2; end -= 2; } }