forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort-array-by-moving-items-to-empty-space.py
59 lines (52 loc) · 1.55 KB
/
sort-array-by-moving-items-to-empty-space.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
# Time: O(n)
# Space: O(n)
# greedy, sort
class Solution(object):
def sortArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def min_moves(d):
def index(x):
return d*(len(nums)-1) if x == 0 else x-d
lookup = [False]*len(nums)
result = len(nums)
for i in xrange(len(nums)):
if lookup[nums[i]]:
continue
l = 0
while not lookup[nums[i]]:
lookup[nums[i]] = True
l += 1
i = index(nums[i])
result -= 1
if l >= 2:
result += 2
return result-2*int(nums[d*(len(nums)-1)] != 0)
return min(min_moves(0), min_moves(1))
# Time: O(n)
# Space: O(n)
# greedy, sort
class Solution2(object):
def sortArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def min_moves(d):
def index(x):
return d*(len(nums)-1) if x == 0 else x-d
a = nums[:]
result = 0
for i in xrange(len(a)):
l, has_zero = 1, (a[i] == 0)
while index(a[i]) != i:
j = index(a[i])
a[i], a[j] = a[j], a[i]
l += 1
has_zero |= (a[i] == 0)
if l >= 2:
result += l-1 if has_zero else l+1
return result
return min(min_moves(0), min_moves(1))