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:
- if i is odd, then
nums[i] >= nums[i - 1]
- 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 becausenums[i-2] (i-2 is odd) >= nums[i - 1]
, so we can swapnums[i - 1]
withnums[i]
, this wouldn’t harm the wiggle pattern to the previous list, and at the same time we meet the rules ati
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]
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!