leecode - 280. Wiggle Sort

Description

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 * 10^4
0 <= nums[i] <= 104
It is guaranteed that there will be an answer for the given input nums.

Follow up: Could you solve the problem in O(n) time complexity?

Solution

Sort and o ( n log ⁡ n ) o(n\log n) o(nlogn)

Sort the list, and then use smaller half and larger half to re-fill the list. Note we do this in a reverse order, to make sure the largest in smaller is not next to the smallest in larger. Eg: [4, 5, 5, 6]

Time complexity: o ( n log ⁡ n ) o(n\log n) o(nlogn)
Space complexity: o ( n ) o(n) o(n)

o ( n ) o(n) o(n)

Solved after help.

ref: https://leetcode.com/problems/wiggle-sort/solutions/71693/my-explanations-of-the-best-voted-algo/

The final result would meet these 2 requirements:

  1. if i is odd, then nums[i] >= nums[i - 1]
  2. if i is even, then nums[i] <= nums[i - 1]

So we just need to adjust to make sure the list meet these rules.

Suppose we have a wiggled list nums[0:i]
When i is odd:

  • if nums[i] >= nums[i - 1], then we don’t need to do anything.
  • if nums[i] < nums[i - 1], then because nums[i-2] (i-2 is odd) >= nums[i - 1], so we can swap nums[i - 1] with nums[i], this wouldn’t harm the wiggle pattern to the previous list, and at the same time we meet the rules at i

When i is even, it’s similar.

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( 1 ) o(1) o(1)

Code

Sort

class Solution:
    def wiggleSort(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        nums.sort()
        smallers, largers = nums[:(len(nums) + 1) // 2], nums[(len(nums) + 1) // 2:]
        nums[::2], nums[1::2] = smallers[::-1], largers[::-1]

Without sort

class Solution:
    def wiggleSort(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        for i in range(1, len(nums)):
            if i % 2 == 0:
                if nums[i] > nums[i - 1]:
                    nums[i], nums[i - 1] = nums[i - 1], nums[i]
            else:
                if nums[i] < nums[i - 1]:
                    nums[i], nums[i - 1] = nums[i - 1], nums[i]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值