Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....

Example:
(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].

Note:
You may assume all input has valid answer.

Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra space?

举例说明:先排序,[1,2,3,4,5,6]

然后从大到小逐个填到奇数位置。 ? 6 ? 5 ? 4

之后再逐个填上偶数位置。 3 6 2 5 1 4

这样的结果由于偶数位置上填的数一定小于他两边的两个奇数位置上填的数。

 class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
snums = sorted(nums)
n = len(nums)
for i in list(range(1, n, 2))+list(range(0,n,2)):
nums[i] = snums.pop()
05-11 17:01
查看更多