Sort Even and Odd Indices Independently
排序一个数组, 偶数index的数字递增, 奇数index的数字递减.
class Solution {
public int[] sortEvenOdd(int[] nums) {
int n = nums.length;
List<Integer> odd = new ArrayList<>();
List<Integer> even = new ArrayList<>();
for(int i = 0; i < nums.length; i++){
if(i % 2 == 0)
even.add(nums[i]);
else
odd.add(nums[i]);
}
Collections.sort(even);
Collections.sort(odd, Collections.reverseOrder());
int[] res = new int[n];
int j = 0;
int k = 0;
for(int i = 0; i < nums.length; i++){
if(i % 2 == 0)
res[i] = even.get(j++);
else
res[i] = odd.get(k++);
}
return res;
}
}