324. Wiggle Sort II
Medium
Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]…
Example 1:
Input: nums = [1, 5, 1, 1, 6, 4]
Output: One possible answer is [1, 4, 1, 5, 1, 6].
Example 2:
Input: nums = [1, 3, 2, 2, 3, 1]
Output: One possible answer is [2, 3, 1, 3, 1, 2].
题意
给定一个数组nums,将数组排序成nums[0] < nums[1] > nums[2] < nums[3] > nums[4] < …的形式
思路
首先将数组排序,然后分为左半部分和右半部分,将左半部分逆序放到偶数位,右半部分逆序放到奇数位,逆序是为了防止排序中两个相邻的数值相等的数恰好也在相邻的奇偶数位。
代码
class Solution {
public void wiggleSort(int[] nums) {
if (nums.length == 0) {
return;
}
Arrays.sort(nums);
int n = nums.length, i = 0, bound = (n&1) == 0? n/2: n/2+1;
int[] left = Arrays.copyOfRange(nums, 0, bound), right = Arrays.copyOfRange(nums, bound, n);
int nl = left.length, nr = right.length;
for (i=0; i<n; ++i) {
if ((i & 1) == 0) {
nums[i] = left[nl - i/2 - 1];
} else {
nums[i] = right[nr - i/2 - 1];
}
}
}
}