# LeetCode.922-按奇偶排序数组 II(Sort Array By Parity II)

### 01 看题和准备

• 2 <= A.length <= 20000

• A.length％2 == 0

• 0 <= A [i] <= 1000

### 02 第一种解法

public int[] sortArrayByParityII(int[] A) {
List<Integer> odd = new ArrayList<Integer>();
List<Integer> even = new ArrayList<Integer>();
for (int num : A) {
if (num%2 == 0) {
} else {
}
}
int j = 0, k = 0;
int[] result = new int[A.length];
for (int i=0; i<result.length; i++) {
if (i%2 == 0) {
result[i] = even.get(j++);
} else {
result[i] = odd.get(k++);
}
}
return result;
}

### 03 第二种解法

public int[] sortArrayByParityII2(int[] A) {
int[] result = new int[A.length];
int j = 0;
for (int i=0; i<A.length; i++) {
if (A[i]%2 == 0) {
result[j] = A[i];
j += 2;
}
}
int k = 1;
for (int i=0; i<A.length; i++) {
if (A[i]%2 != 0) {
result[k] = A[i];
k += 2;
}
}
return result;
}

### 04 第三种解法

public int[] sortArrayByParityII3(int[] A) {
int[] result = new int[A.length];
int j = 0, k = 1;
for (int i=0; i<A.length; i++) {
if (A[i]%2 == 0) {
result[j] = A[i];
j += 2;
} else {
result[k] = A[i];
k += 2;
}
}
return result;
}

### 05 第四种解法

public int[] sortArrayByParityII4(int[] A) {
int i = 0, j = A.length-1, n = A.length;
while (i < n && j >= 1) {
if (A[i]%2 == 1 && A[j]%2 == 0) {
int tem = A[j];
A[j] = A[i];
A[i] = tem;
}
if (A[i]%2 == 0) {
i += 2;
}
if (A[j]%2 == 1) {
j -= 2;
}
}
return A;
}

### 06 小结

posted @ 2019-06-15 13:42 程序员小川 阅读(...) 评论(...) 编辑 收藏