原题
Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]…
Example:
Input: nums = [3,5,2,1,6,4]
Output: One possible answer is [3,5,1,6,2,4]
解法
遍历nums, 如果偶数index的值比下一个值大, 则交换位置; 如果奇数index的值比下一个值小, 则交换位置.
Time: O(n)
Space: O(1)
代码
class Solution:
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)-1):
if i%2 == 1 and nums[i]< nums[i+1]:
nums[i], nums[i+1] = nums[i+1], nums[i]
elif i%2 == 0 and nums[i]> nums[i+1]:
nums[i], nums[i+1] = nums[i+1], nums[i]