[LeetCode] 280. Wiggle Sort

Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].

Thought process:
The result needs to guarantee that when i is odd, nums[i] >= nums[i - 1]; when i is even, nums[i] <= nums[i - 1]. The idea is that, whenever we see a nums[i] that violates this rule, we swap it with nums[i - 1]. This will work because if i is odd and nums[i] < nums[i - 1], nums[i] is also always less than nums[i - 2]; if i is even and nums[i] > nums[i - 1], nums[i] is also always larger than nums[i - 2]. So swapping will not violate the relationship between nums[i - 1] and nums[i - 2].

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
public:
    void wiggleSort(vector<int>& nums) {
        for (int i = 1; i < nums.size(); i++) {
            if (((i & 1) && nums[i] < nums[i - 1]) || (!(i & 1) && nums[i] > nums[i - 1])) {
                swap(nums[i], nums[i - 1]);
            }
        }
    }
};

Time complexity: O(n).

Comments

Popular posts from this blog

[LeetCode] 631. Design Excel Sum Formula

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary