324. Wiggle Sort II
Published in
May 30, 2023
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 = [1,5,1,1,6,4]
Output: [1,6,1,5,1,4]
Explanation: [1,4,1,5,1,6] is also accepted.
Example 2:
Input: nums = [1,3,2,2,3,1]
Output: [2,3,1,3,1,2]
思路Coding化:
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
nums.sort()
mid = (n - 1) // 2
nums[::2], nums[1::2] = nums[mid::-1], nums[:mid:-1]
#nums[::2] index 0 2 4..
#nums[1::2] index 1 3 5 ...
#nums[mid::-1] 從中位數往前到index 0
#nums[:mid:-1] 從最後一位往前至中位數(不含中位數)
Time Complexity:O(n log n)
Space Complexity: O(1)