forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rearrange-array-elements-by-sign.py
68 lines (61 loc) · 1.53 KB
/
rearrange-array-elements-by-sign.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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Time: O(n)
# Space: O(1)
# two pointers
class Solution(object):
def rearrangeArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
pos, neg = 0, 1
result = [0]*len(nums)
for x in nums:
if x > 0:
result[pos] = x
pos += 2
else:
result[neg] = x
neg += 2
return result
# Time: O(n)
# Space: O(1)
# generator
class Solution2(object):
def rearrangeArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
def pos():
for x in nums:
if x > 0:
yield x
def neg():
for x in nums:
if x < 0:
yield x
gen_pos = pos()
gen_neg = neg()
return [next(gen_pos) if i%2 == 0 else next(gen_neg) for i in xrange(len(nums))]
# Time: O(n)
# Space: O(n)
# array, implementation
class Solution3(object):
def rearrangeArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
pos, neg = [], []
for i in reversed(xrange(len(nums))):
if nums[i] > 0:
pos.append(nums[i])
else:
neg.append(nums[i])
result = []
for i in xrange(len(nums)):
if i%2 == 0:
result.append(pos.pop())
else:
result.append(neg.pop())
return result