Python easy to understand solution with Flag


  • 0
    S

    Use a flag to mark the targeting order (increasing / decreasing) at each index

    '''

    def wiggleSort(self, nums):
        # a flag to record checking conditions
        to_increase = True
        for i in range(len(nums)-1):
            if (to_increase and (nums[i] > nums[i+1])) or (not to_increase and (nums[i] < nums[i+1])):
                nums[i], nums[i+1] = nums[i+1], nums[i]
            
            # flag alternates at every step 
            to_increase = not to_increase
    

    '''


Log in to reply
 

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