题目:
给你一个整数数组 nums,将它重新排列成 nums[0] < nums[1] > nums[2] < nums[3]… 的顺序。
你可以假设所有输入数组都可以得到满足题目要求的结果。
解答:
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
#桶排序
n=len(nums)
bucket=[0]*5001
for num in nums:
bucket[num]+=1
if n%2==0:
big=n-1
small=n-2
else:
small=n-1
big=n-2
j=5000
#将桶中较大的数交叉插入结果中
for i in range(1,big+1,2):
while bucket[j]==0:
j-=1
nums[i]=j
bucket[j]-=1
#将桶中较小的数交叉插入结果中
for i in range(0,small+1,2):
while bucket[j]==0:
j-=1
nums[i]=j
bucket[j]-=1
return nums