[LeetCode] (medium) 324. Wiggle Sort II

https://leetcode.com/problems/wiggle-sort-ii/

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].

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;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值