C++ O(n) concise solution.


  • 7
    C
    void wiggleSort(vector<int>& nums) {
        for (int i=0; i<(int)nums.size()-1; i++) {
            if (i%2==0 && nums[i]>nums[i+1])
                swap(nums[i], nums[i+1]);
            if (i%2==1 && nums[i]<nums[i+1])
                swap(nums[i], nums[i+1]);
        }
    }

  • 0
    S

    try [1,2,2,1,2,1,1,1,1,2,2,2]...


  • 0
    Z

    Hi, just curious why you need the (int)here-----(int)nums.size()-1?? I try to run it without (int), and when the input is an empty vector, it will have a run time error..


  • 0
    K

    outputs: 1 2 1 2 1 2 1 1 1 2 2 2
    looks fine


  • 0
    K

    Without using (int), nums.size()-1 will be max of unsigned int. Then in the loop, num[i] will visit somewhere that out of index, which will cause run time error.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.