280. Wiggle Sort

Given an unsorted arraynums, reorder it in-place such thatnums[0] <= nums[1] >= nums[2] <= nums[3]....

Example:

Input:
nums = [3,5,2,1,6,4]
Output: One possible answer is [3,5,1,6,2,4]

Thoughts:

  1. Naive: traverse through the element (sort each two element (from [i, i + 2) according to alternative order (ascending vs decending)
  2. Window of 2: always ranking nums[i-1] and num[i] with the alternating order: when i is odd, then nums[i-1] should be <= nums[i]; when i is even (Excepet 0), nums[i-1] should be >= nums[i]

Code

class Solution(object):
    def wiggleSort(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        for i in range(len(nums)):
            nums[i: i+ 2] = sorted(nums[i: i + 2], reverse = i%2)

Code

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

results matching ""

    No results matching ""