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?
一刷
題解:
方法1蛤肌, 最簡(jiǎn)單的做法, 排序,然后兩邊取
方法2, 先找到數(shù)組的中位數(shù)挂签,用類似于215 find largest kth的方法亏掀,然后把小于中位數(shù)的放左邊钉汗,大于的放右邊砸讳,然后兩邊取豹绪,space complexity O(n)
方法3坛怪, 要達(dá)到空間復(fù)雜度為O(1)墅拭,將nums數(shù)組的下標(biāo)x通過函數(shù)idx()從[0, 1, 2, ... , n - 1, n] 映射到 [1, 3, 5, ... , 0, 2, 4, ...]活玲,得到新下標(biāo)ix
public void wiggleSort(int[] nums) {
int median = findKthLargest(nums, (nums.length + 1) / 2);
int n = nums.length;
int left = 0, i = 0, right = n - 1;
while (i <= right) {
if (nums[newIndex(i,n)] > median) {
swap(nums, newIndex(left++,n), newIndex(i++,n));
}
else if (nums[newIndex(i,n)] < median) {
swap(nums, newIndex(right--,n), newIndex(i,n));
}
else {
i++;
}
}
}
private int newIndex(int index, int n) {
return (1 + 2*index) % (n | 1);
}