-
Notifications
You must be signed in to change notification settings - Fork 90
/
Count of Smaller Number.py
70 lines (56 loc) · 1.57 KB
/
Count of Smaller Number.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
"""
Give you an integer array (index from 0 to n-1, where n is the size of this array, value from 0 to 10000) and an query
list. For each query, give you an integer, return the number of element in the array that are smaller that the given
integer.
Example
For array [1,2,7,8,5], and queries [1,8,5], return [0,4,2]
Note
We suggest you finish problem Segment Tree Build and Segment Tree Query II first.
Challenge
Could you use three ways to do it.
Just loop
Sort and binary search
Build Segment Tree and Search.
"""
__author__ = 'Daniel'
class Solution:
def countOfSmallerNumber(self, A, queries):
# return self.loop(A, queries)
return self.search(A, queries)
def loop(self, A, queries):
"""
O(N*k)
"""
cnt = dict(zip(queries, [0 for _ in queries]))
for elt in A:
for k in cnt.keys():
if elt<k:
cnt[k] += 1
return [cnt[i] for i in queries]
def search(self, A, queries):
"""
O(nlgn + klgn)
"""
A.sort()
ret = []
for q in queries:
ind = self.bin_search(A, q)
while ind>=0 and A[ind]==q:
ind -= 1
ret.append(ind+1)
return ret
def bin_search(self, A, t):
b = 0
e = len(A)
while b<e:
m = (b+e)/2
if t==A[m]:
return m
elif t < A[m]:
e = m
else:
b = m+1
return b-1
def segment_tree(self, A, queries):
# TODO
pass