one pass method with wile
class Solution {
public int[] sortArrayByParityII(int[] A) {
int i = 1, j = 0;
int N = A.length;
while (i < N) {
for (;i < N && A[i] % 2 == 1; i += 2);
if (i >= N) return A;
for (;j < N && A[j] % 2 == 0; j += 2);
int t = A[i];
A[i] = A[j];
A[j] = t;
}
return A;
}
}
and use for
class Solution {
public int[] sortArrayByParityII(int[] A) {
int j = 0;
int N = A.length;
for (int i = 1; i < N; i += 2) {
if (A[i] % 2 == 0) {
for (;j < N && A[j] % 2 == 0; j += 2);
int t = A[i];
A[i] = A[j];
A[j] = t;
}
}
return A;
}
}
leetcode 922. Sort Array By Parity II
原文:https://www.cnblogs.com/exhausttolive/p/10657482.html