关键词
奇偶分区 two pointers,
题目描述
https://leetcode.com/problems/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.
Example 1:
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.
Note:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
博主提交的代码
IN-PLACE 版本
思路错了,错误代码,别看,这个问题本质就是需要同时判断奇偶再进行交换,我这个思路已经不进行
class Solution {
public int[] sortArrayByParityII(int[] A) {
int evenIndex = 0;
int oddIndex = 1;
for(int i = 0; i < A.length;){
if(isEven(i) && !isEven(A[i])){
oddIndex+=2;
} else if(!isEven(i) && isEven(A[i])){
int tmp = A[evenIndex];
A[i] = tmp;
oddIndex+=2;
} else if(isEven(i)) {
evenIndex+=2;
i++;
} else if(!isEven(i)){
oddIndex+=2;
i++;
}
}
return A;
}
public boolean isEven(int input){
if( (input & 1) == 0){
return true;
} else{
return false;
}
}
}
非IN-PLACE 版本
class Solution {
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[j] % 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;
}
}
其他人优秀的解法
class Solution {
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[j] % 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;
}
}