Leetcode学习笔记:#922. Sort Array By Parity II
Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.
Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.
You may return any answer array that satisfies this condition.
实现:
public int[] sortArrayByParityII(int[] A){
int i =0, j = 1, n = A.length;
while(i < n && j < n){
while(i < n && A[i] % 2 == 0){
i+=2;
}
while(j < n && A[i] % 2 == 1){
j+=2;
}
if(i < n && j < n){
swap(A, i, j);
}
}
return A;
}
private void swap(int[] A, int i, int j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
思路:
两个指针一次遍历,一个指针i从0开始,一个指针j从1开始,i每遇到一个偶数便+2挪到下一个偶数,j遇到奇数+2挪到下一个奇数,直到遇到非奇数停止产生交换。