LeetCode 280. Wiggle Sort

Description

https://leetcode.com/problems/wiggle-sort/

Given an integer array nums, reorder it such that nums[0] <= nums[1] >= nums[2] <= nums[3]....

You may assume the input array always has a valid answer.

Example 1:

Input: nums = [3,5,2,1,6,4]
Output: [3,5,1,6,2,4]
Explanation: [1,6,2,5,3,4] is also accepted.

Example 2:

Input: nums = [6,6,5,6,3,8]
Output: [6,6,5,6,3,8]

Constraints:

  • 1 <= nums.length <= 5 * 104
  • 0 <= nums[i] <= 104
  • It is guaranteed that there will be an answer for the given input nums.

Follow up: Could you do it without sorting the array?

Explanation

Sort the list. Then use a temp array, for odds positions, append an element from the beginning of the list. For even positions, append an element from the end of the list.

Python Solution

class Solution:
    def wiggleSort(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        
        temps = list(sorted(nums))
        
        results = []
        for i in range(len(temps)):
            if i % 2 == 0:
                results.append(temps.pop(0))
            else:
                results.append(temps.pop())
            
            i += 1
            
        
        for i, num in enumerate(results):
            nums[i] = results[i]
  • Time Complexity: O(NlogN).
  • Space Complexity: O(N).

Leave a Reply

Your email address will not be published.