Given an unsorted array nums
, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]...
.
For example, given nums = [3, 5, 2, 1, 6, 4]
, one possible answer is [1, 6, 2, 5, 3, 4]
.
观察wiggle sort之后的结果可知:
nums[even] <= nums[even+1] (index从0开始)
nums[odd] >= nums[odd+1]
依次检查每一个元素,如果不符合这个条件就和下一个元素交换一下。
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
for i in range(n-1):
if i%2 == 0 and nums[i] > nums[i+1]:
nums[i], nums[i+1] = nums[i+1], nums[i]
elif i%2 == 1 and nums[i] < nums[i+1]:
nums[i], nums[i+1] = nums[i+1], nums[i]