Skip to content

Commit 49a4389

Browse files
author
weiy
committed
wiggle sort II medium
1 parent ba51113 commit 49a4389

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

Sorted/WiggleSortII.py

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
"""
2+
Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....
3+
4+
Example 1:
5+
6+
Input: nums = [1, 5, 1, 1, 6, 4]
7+
Output: One possible answer is [1, 4, 1, 5, 1, 6].
8+
Example 2:
9+
10+
Input: nums = [1, 3, 2, 2, 3, 1]
11+
Output: One possible answer is [2, 3, 1, 3, 1, 2].
12+
Note:
13+
You may assume all input has valid answer.
14+
15+
Follow Up:
16+
Can you do it in O(n) time and/or in-place with O(1) extra space?
17+
18+
1 锁了,暂不能做。
19+
20+
II 的话规则:
21+
单数位 大于 双数位。
22+
23+
思路:
24+
25+
一开始的话想到的是排序后,取中间,然后后半部分按从大到小铺在单数位上。
26+
前半部分按从大到小从末尾的双数位开始向前铺。
27+
28+
这个思路一开始是可以的,不过忽略了相等的部分,因为有可能铺的时候相遇。所以注意下,相等的等上面的过程铺完之后,用于补剩下的部分。
29+
30+
进阶要求是:
31+
O(n) 时间,O(1) 空间。
32+
33+
排序的话 O(n log n),不符合要求。
34+
35+
这个思路的关键点是找到中位数,但怎么在 O(n) 时间 O(1) 空间找到中位数呢?
36+
37+
下面是我的思考,没有最终实现。
38+
39+
1. 先找到里面最小的元素并获取出总长度。
40+
2. 过一遍,找出 总长度 // 2 个比它大的元素,顺便记录出这里面的最大值。
41+
3. 再过一遍,找出 比 2. 中最大值大的 元素。
42+
4. 再找出比它大的元素个数 - 总长度 // 2
43+
5. 若刚好有 总长度 // 2 个那么它就是中位数,否则它就是第 k(比它大的元素个数 - 总长度 // 2) 大个元素。
44+
6. 缩小了范围。重复步骤...
45+
46+
时间复杂度非常依赖运气...
47+
48+
下面直接用了排序,没有达成进阶条件,待改进。
49+
50+
beat
51+
68%
52+
53+
测试地址:
54+
https://leetcode.com/problems/wiggle-sort-ii/description/
55+
56+
57+
"""
58+
class Solution(object):
59+
def wiggleSort(self, nums):
60+
"""
61+
:type nums: List[int]
62+
:rtype: void Do not return anything, modify nums in-place instead.
63+
"""
64+
65+
nums.sort()
66+
middle = nums[len(nums) // 2]
67+
larger = [i for i in nums[len(nums)//2:] if i != middle]
68+
smaller = [i for i in nums[:len(nums)//2] if i != middle]
69+
equal = [i for i in nums if i == middle]
70+
71+
larger.reverse()
72+
smaller.reverse()
73+
length = len(nums)
74+
odd = 1
75+
even = length - 1 if (length-1) % 2 == 0 else length - 2
76+
77+
for i in larger:
78+
# try:
79+
nums[odd] = i
80+
81+
odd += 2
82+
83+
for i in smaller:
84+
nums[even] = i
85+
86+
even -= 2
87+
88+
while even >= 0:
89+
nums[even] = equal.pop()
90+
even -= 2
91+
92+
while odd < length:
93+
nums[odd] = equal.pop()
94+
odd += 2

0 commit comments

Comments
 (0)