按奇偶排序數組
給定一個非負整數數組 A,返回一個數組,在該數組中, A 的所有偶數元素之後跟着所有奇數元素。
你可以返回滿足此條件的任何數組作爲答案。
示例:
輸入:[3,1,2,4]
輸出:[2,4,3,1]
輸出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也會被接受。
提示:
1 <= A.length <= 5000
0 <= A[i] <= 5000
思路
1.雙指針法,左右指針同時掃描,如果左邊爲奇數,右邊爲偶數,則交換,否則指針向中間靠攏
public int[] sortArrayByParity(int[] A) {
if (A == null || A.length == 1) {
return A;
}
int left = 0;
int right = A.length - 1;
int temp;
while (left < right) {
//左邊爲奇數,右邊爲偶數,互換值
if ((A[left] & 1) == 1 && (A[right] & 1) == 0) {
tem = A[left];
A[left] = A[right];
A[right] = tem;
} else if ((A[left] & 1) == 0) {
//左邊爲偶數,指針向右移動
left++;
} else if ((A[right] & 1) == 1) {
//右邊爲奇數,指針向左移動
right--;
}
}
return A;
}