description: Given an array with positive and negative integers. Re-range it to interleaving with positive and negative integers.
Notice
You are not necessary to keep the original order of positive integers or negative integers.
Have you met this question in a real interview? Yes 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.
同樣是使用two pointers的算法進(jìn)行處理。但是此時的two pointer的方法是使用的同向的雙指針進(jìn)行的
class Solution { /** * @param A: An integer array. * @return: void */ public void rerange(int[] A) { // write your code here if (A == null || A.length == 0 || A.length == 1) { return; } int pos = 0; int neg = 0; for (int i = 0; i < A.length; i++) { if (A[i] < 0) { neg++; } else { pos++; } } int posind = 1; int negind = 0; if (neg < pos) { posind = 0; negind = 1; } while (posind < A.length && negind < A.length) { if (A[posind] > 0) { posind += 2; } if (A[negind] < 0) { negind += 2; } if (posind < A.length && negind < A.length) { swap(A, posind, negind); } } } PRivate void swap(int[] A, int left, int right) { int temp = A[left]; A[left] = A[right]; A[right] = temp; }}
|
新聞熱點(diǎn)
疑難解答