Question
Solution
题目大意:给一个int数组,一半是奇数一半是偶数,分别对偶数数和奇数数排序并要求这个数本身是偶数要放在偶数位上
思路:把奇数数和偶数数筛选出来后对其分别排序,再按奇偶索引放到原数组上
Java实现:
public int[] sortArrayByParityII(int[] A) {
List<Integer> oddList = new ArrayList<>();
List<Integer> evenList = new ArrayList<>();
for (int a : A) {
if (a % 2 == 0) evenList.add(a);
else oddList.add(a);
}
Collections.sort(oddList);
Collections.sort(evenList);
for (int i = 0; i < oddList.size(); i++) {
A[2 * i] = evenList.get(i);
A[2 * i + 1] = oddList.get(i);
}
return A;
}