https://leetcode.com/problems/wiggle-sort-ii/
Given an unsorted array
nums
, reorder it such thatnums[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].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?
毫无头绪,参考:https://blog.csdn.net/qq508618087/article/details/51337187
重点是实现下标的重映射,等价于在逻辑上把原数组的奇数位放左边偶数位放右边组成新数组,然后使用3-sort的方法即可
class Solution {
public:
void wiggleSort(vector<int>& nums) {
static int fast_io = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();
nth_element(nums.begin(), nums.begin()+nums.size()/2, nums.end());
int len = nums.size(), lo = 0, hi = nums.size()-1, mid = nums[nums.size()/2];
auto index = [=](int pos){return (1+2*pos)%(len|1);};
int cur = 0;
while(cur <= hi){
if(nums[index(cur)] > mid){
swap(nums[index(cur)], nums[index(lo)]);
++cur; ++lo;
}else if(nums[index(cur)] < mid){
swap(nums[index(cur)], nums[index(hi)]);
--hi;
}else{
++cur;
}
}
return;
}
};