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

01 看题和准备

• 1 <= A.length <= 5000

• 0 <= A[i] <= 5000

02 第一种解法

public int[] sortArrayByParity(int[] A) {
List<Integer> list = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
int n = A.length;
for (int i=0; i<n; i++) {
if (A[i]%2 == 0 ) {
} else {
}
}
int[] result = new int[n];
int index = 0;
for (int j=0; j<list.size(); j++) {
result[index++] = list.get(j);
}
for (int j=0; j<list2.size(); j++) {
result[index++] = list2.get(j);
}
return result;
}

03 第二种解法

public int[] sortArrayByParity2(int[] A) {
int n = A.length, index = 0;
int[] result = new int[n];
for (int i=0; i<n; i++) {
if (A[i]%2 == 0 ) {
result[index++] = A[i];
}
}
for (int j=0; j<n; j++) {
if (A[j]%2 != 0 ) {
result[index++] = A[j];
}
}
return result;
}

04 第三种解法

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

05 小结

posted @ 2019-06-08 17:09 程序员小川 阅读(...) 评论(...) 编辑 收藏