Wiggle Sort

Problem: Wiggle Sort

The requirements can be easily explained as odd position numbers need to be smaller than previous one, and even position numbers need to be bigger than previous number. We can scan through the numbers and when we get wrong numbers we just swap them. It can be easily proved that the swapping won't make previous numbers disagree to the requirement.

Code in Python:

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 xrange(1, len(nums)):
            if i % 2 and nums[i] < nums[i-1]: nums[i], nums[i-1] = nums[i-1], nums[i]
            elif not i % 2 and nums[i] > nums[i-1]: nums[i], nums[i-1] = nums[i-1], nums[i]

results matching ""

    No results matching ""