O(n) solution in Python


  • 0
    R

    A direction variable is used to indicate an increase/decrease. dir = 1 indicates an increase, and dir = 0 indicates a decrease.

    class Solution(object):
        def wiggleSort(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            def swap(nums, i, j):
                temp = nums[i]
                nums[i] = nums[j]
                nums[j] = temp
                
            dir = 1
            for i in range(1, len(nums)):
                if dir == 1:
                    if nums[i-1] > nums[i]:
                        swap(nums, i-1, i)
                if dir == 0:
                    if nums[i-1] < nums[i]:
                        swap(nums, i-1, i)
                dir = not dir
    
    
    

Log in to reply
 

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