1 """
2 Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....
3 Example 1:
4 Input: nums = [1, 5, 1, 1, 6, 4]
5 Output: One possible answer is [1, 4, 1, 5, 1, 6].
6 Example 2:
7 Input: nums = [1, 3, 2, 2, 3, 1]
8 Output: One possible answer is [2, 3, 1, 3, 1, 2].
9 """
10 """
11 先排序,再折半拆成两个子数组,再归并
12 但本题的关键是需要对两个子数组由后向前取元素
13 """
14 class Solution:
15 def wiggleSort(self, nums):
16 """
17 Do not return anything, modify nums in-place instead.
18 """
19 l = sorted(nums)
20 mid = (len(l)+1)//2
21 l1 = l[:mid]
22 l2 = l[mid:]
23 k, i, j = 0, len(l1)-1, len(l2)-1 #!!!逆着合并 测试[4, 5, 5, 6]
24 while i >= 0 or j >= 0: #bug 写成了i>0
25 if i >= 0:
26 nums[k] = l1[i]
27 i -= 1
28 k += 1
29 if j >= 0:
30 nums[k] = l2[j]
31 j -= 1
32 k += 1
33 if __name__ == '__main__':
34 nums = [1,3,2,2,3,1]
35 ans = Solution()
36 res = ans.wiggleSort(nums)