forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate-sorted-array-through-instructions.py
99 lines (89 loc) · 3.26 KB
/
create-sorted-array-through-instructions.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# Time: O(nlogm)
# Space: O(m)
class BIT(object): # 0-indexed.
def __init__(self, n):
self.__bit = [0]*(n+1) # Extra one for dummy node.
def add(self, i, val):
i += 1 # Extra one for dummy node.
while i < len(self.__bit):
self.__bit[i] += val
i += (i & -i)
def query(self, i):
i += 1 # Extra one for dummy node.
ret = 0
while i > 0:
ret += self.__bit[i]
i -= (i & -i)
return ret
class Solution(object):
def createSortedArray(self, instructions):
"""
:type instructions: List[int]
:rtype: int
"""
MOD = 10**9 + 7
bit = BIT(max(instructions))
result = 0
for i, inst in enumerate(instructions):
inst -= 1
result += min(bit.query(inst-1), i-bit.query(inst))
bit.add(inst, 1)
return result % MOD
# Time: O(nlogn)
# Space: O(n)
import itertools
class Solution_TLE(object):
def createSortedArray(self, instructions):
"""
:type instructions: List[int]
:rtype: int
"""
MOD = 10**9 + 7
def smallerMergeSort(idxs, start, end, counts):
if end - start <= 0: # The size of range [start, end] less than 2 is always with count 0.
return 0
mid = start + (end - start) // 2
smallerMergeSort(idxs, start, mid, counts)
smallerMergeSort(idxs, mid + 1, end, counts)
r = start
tmp = []
for i in xrange(mid+1, end + 1):
# Merge the two sorted arrays into tmp.
while r <= mid and idxs[r][0] < idxs[i][0]:
tmp.append(idxs[r])
r += 1
tmp.append(idxs[i])
counts[idxs[i][1]] += r - start
while r <= mid:
tmp.append(idxs[r])
r += 1
# Copy tmp back to idxs
idxs[start:start+len(tmp)] = tmp
def largerMergeSort(idxs, start, end, counts):
if end - start <= 0: # The size of range [start, end] less than 2 is always with count 0.
return 0
mid = start + (end - start) // 2
largerMergeSort(idxs, start, mid, counts)
largerMergeSort(idxs, mid + 1, end, counts)
r = start
tmp = []
for i in xrange(mid+1, end + 1):
# Merge the two sorted arrays into tmp.
while r <= mid and idxs[r][0] <= idxs[i][0]:
tmp.append(idxs[r])
r += 1
if r <= mid:
tmp.append(idxs[i])
counts[idxs[i][1]] += mid - r + 1
while r <= mid:
tmp.append(idxs[r])
r += 1
# Copy tmp back to idxs
idxs[start:start+len(tmp)] = tmp
idxs = []
smaller_counts, larger_counts = [[0] * len(instructions) for _ in xrange(2)]
for i, inst in enumerate(instructions):
idxs.append((inst, i))
smallerMergeSort(idxs[:], 0, len(idxs)-1, smaller_counts)
largerMergeSort(idxs, 0, len(idxs)-1, larger_counts)
return sum(min(s, l) for s, l in itertools.izip(smaller_counts, larger_counts)) % MOD