Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 280. Wiggle Sort #280

Open
grandyang opened this issue May 30, 2019 · 0 comments
Open

[LeetCode] 280. Wiggle Sort #280

grandyang opened this issue May 30, 2019 · 0 comments

Comments

@grandyang
Copy link
Owner

grandyang commented May 30, 2019

 

Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....

Example:

Input: nums = [3,5,2,1,6,4]
Output: One possible answer is [3,5,1,6,2,4]

 

这道题让我们求摆动排序,跟 Wiggle Sort II 相比起来,这道题的条件宽松很多,只因为多了一个等号。由于等号的存在,当数组中有重复数字存在的情况时,也很容易满足题目的要求。这道题先来看一种时间复杂度为 O(nlgn) 的方法,思路是先给数组排个序,然后只要每次把第三个数和第二个数调换个位置,第五个数和第四个数调换个位置,以此类推直至数组末尾,这样就能完成摆动排序了,参见代码如下:

 

解法一:

class Solution {
public:
    void wiggleSort(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        if (nums.size() <= 2) return;
        for (int i = 2; i < nums.size(); i += 2) {
            swap(nums[i], nums[i - 1]);
        }
    }
};

 

这道题还有一种 O(n) 的解法,根据题目要求的 nums[0] <= nums[1] >= nums[2] <= nums[3]....,可以总结出如下规律:

当i为奇数时,nums[i] >= nums[i - 1]

当i为偶数时,nums[i] <= nums[i - 1]

那么只要对每个数字,根据其奇偶性,跟其对应的条件比较,如果不符合就和前面的数交换位置即可,参见代码如下:

 

解法二:

class Solution {
public:
    void wiggleSort(vector<int>& nums) {
        if (nums.size() <= 1) return;
        for (int i = 1; i < nums.size(); ++i) {
            if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) {
                swap(nums[i], nums[i - 1]);
            }
        }
    }
};

 

Github 同步地址:

#280

 

类似题目:

Wiggle Sort II

Sort Colors

 

参考资料:

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

https://leetcode.com/problems/wiggle-sort/discuss/71692/Java-O(N)-solution

https://leetcode.com/problems/wiggle-sort/discuss/71688/4-lines-O(n)-C%2B%2B

https://leetcode.com/problems/wiggle-sort/discuss/71693/My-explanations-of-the-best-voted-Algo

 

LeetCode All in One 题目讲解汇总(持续更新中...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant