Leetcode - 922 Sort Array By Parity II (Easy)
题目描述:给定一个数组,让数组中所有的偶数在偶数下标位置,所有的奇数在奇数下标位置。
Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
public int[] sortArrayByParityII(int[] A) {
int[] newA = new int[A.length];
int evenIndex = 0, oddIndex = 1;
for (int i = 0; i < A.length; i++) {
if (A[i] % 2 == 0) {
newA[evenIndex] = A[i];
evenIndex += 2;
} else {
newA[oddIndex] = A[i];
oddIndex += 2;
}
}
return newA;
}