Ruby solution, I think it works but not accepted due to special judge.


  • -1
    S

    def wiggle_sort(nums)

    i = 1
    while i < nums.size
        
            if nums[i - 1] > nums[i] # so nums[0]<nums[1]
                nums[i - 1], nums[i] = nums[i], nums[i - 1]
            end
            
            if i < nums.size - 1 && nums[i] < nums[i + 1] #if nums[1] < nums[2], then nums[0]<nums[2],swap1,2
                nums[i], nums[i + 1] = nums[i + 1], nums[i] # then nums[0]<nums[1]>nums[2]
            end
        
        i += 2 
    

    nums[0-2] is in order, then judge nums[3], if nums[2] > nums[3], then nums[1] > nums[3],swap2,3

    end
    

    end


Log in to reply
 

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