题目要求:
将一个数组变成变成摇摆序列
Examples:
(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6].
(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2].
解题思路:
- 解法一定不唯一,但这一定是最保险的方法。
# Time: O(nlogn)
# Space: O(n)
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums.sort() #复杂度O(nlogn)
med = len(nums[::2]) - 1
nums[::2], nums[1::2] = nums[med::-1], nums[:med:-1]
#把小的数字放到奇数位置,把大的数字放到偶数位置。
if __name__ == "__main__":
A = [2, 1, 1, 0, 0, 2]
Solution.wiggleSort(self=None, nums=A)
print(A)