Straightforward sorting and wiggle filling


  • 0

    I see that no one has posted this solution yet so I'll put it here for completeness.

    Instead of do "wiggle" when swapping, we sort the array first and fill the array "wigglely", that is, we fill the array with the min from first half of sorted array then with the min from second half of the sorted array. The order is guaranteed by initial sorting.

      def wiggleSort(self, nums):
        nums.sort()
        n, left, right = len(nums), 1,  (len(nums) + 1) // 2
        while left < right and right < n:
          nums[left], nums[right] = nums[right], nums[left]
          left += 1
          nums[left], nums[right] = nums[right], nums[left]
          left += 1
          right += 1
    

Log in to reply
 

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