Leetcode_Sort --324. Wiggle Sort II [medium]

Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]….
给定一个未排序的数组nums,使它重新排序为:nums[0] < nums[1] > nums[2] < nums[3]…. 【摆动排序】

Example 1:


Input: Input: nums = [1, 5, 1, 1, 6, 4]nums = [1, 
Output: One possible answer is [1, 4, 1, 5, 1, 6].

Example 2:

Input: nums = [1, 3, 2, 2, 3, 1]
Output: 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?

Solution:

Python

(1)
def WiggleSort(self,nums):
    nums.sort()
    half = len(nums[::2])
    nums[::2] = nums[:half][::-1]
    nums[1::2] = nums[half:][::-1]

(2)
def WiggleSort(self,nums):
    '''
    pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
    list.pop([index=-1])
    '''
    arr = sorted(nums)
    for i in range(1, len(nums), 2): nums[i] = arr.pop()
    for i in range(0, len(nums), 2): nums[i] = arr.pop()

猜你喜欢

转载自blog.csdn.net/y_xiansheng/article/details/82319546
今日推荐