forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwiggle-sort.py
27 lines (24 loc) · 804 Bytes
/
wiggle-sort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Time: O(n)
# Space: O(1)
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for i in xrange(1, len(nums)):
if ((i % 2) and nums[i - 1] > nums[i]) or \
(not (i % 2) and nums[i - 1] < nums[i]):
# Swap unordered elements.
nums[i - 1], nums[i] = nums[i], nums[i - 1]
# time: O(nlogn)
# space: O(n)
class Solution2(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums.sort()
med = (len(nums) - 1) // 2
nums[::2], nums[1::2] = nums[med::-1], nums[:med:-1]