Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]….
Example:
(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6].
(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2].
Note:
You may assume all input has valid answer.
Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra space?
最朴素的方法是将数组排序分为两部分,将两部分分别放置在偶数位置和奇数位置。
为了满足OnO1,先利用findkth找到median,然后利用mapidx映射的关系将数组中元素置换。
public class Solution {
public void wiggleSort(int[] nums) {
if (nums == null || nums.length == 0) return;
int n = nums.length;
int median_idx = n % 2 == 0 ? n/2-1 : n/2;
int median = findkth(nums, 0, nums.length-1, median_idx);
int left = 0, right = n-1, i = 0;
while (i <= right) {
if (nums[mapidx(i, n)] > median) swap(nums, mapidx(i++, n), mapidx(left++, n));
else if (nums[mapidx(i, n)] < median) swap(nums, mapidx(i, n), mapidx(right--, n));
else i++;
}
}
public int mapidx(int i, int n) {
return (2 * i + 1) % (n | 1);
}
public int findkth(int[] nums, int start, int end, int k) {
if (start > end) return Integer.MAX_VALUE;
int pivot = nums[end];
int left = start;
for (int i = start; i < end; i++) {
if (nums[i] < pivot) swap(nums, left++, i);
}
swap(nums, left, end);
if (left == k) return nums[left];
else if (left > k) return findkth(nums, start, left-1, k);
return findkth(nums, left+1, end, k);
}
public void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}