给定一个非负整数数组 A
, A 中一半整数是奇数,一半整数是偶数。
对数组进行排序,以便当 A[i]
为奇数时,i
也是奇数;当 A[i]
为偶数时, i
也是偶数。
你可以返回任何满足上述条件的数组作为答案。
示例:
输入:[4,2,5,7] 输出:[4,5,2,7] 解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
提示:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
import java.util.Stack;
public class Solution922 {
public int[] sortArrayByParityII(int[] A) {
int[] out = new int[A.length];
Stack<Integer> odd = new Stack<>();
Stack<Integer> even = new Stack<>();
for (int i = 0; i < A.length; i++) {
if (A[i] % 2 == 0) {
even.add(A[i]);
} else {
odd.add(A[i]);
}
}
for (int i = 0; i < out.length; i++) {
if (i % 2 == 0) {
out[i] = even.pop();
} else {
out[i] = odd.pop();
}
}
return out;
}
public static void main(String[] args) {
Solution922 s = new Solution922();
int[] A = { 4, 2, 5, 7 };
for (int n : A) {
System.out.println(n);
}
System.out.println(s.sortArrayByParityII(A));
for (int n : s.sortArrayByParityII(A)) {
System.out.println(n);
}
}
}