-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count of Smaller Numbers After Self
34 lines (31 loc) · 1.19 KB
/
Count of Smaller Numbers After Self
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
class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
smaller = [0]*len(nums)
def helper(left,right):
if left==right:
return [left]
mid = left + (right-left)// 2
left_part = helper(left,mid)
right_part = helper(mid+1,right)
left_ptr = 0
right_ptr = 0
ans = []
smaller_after = 0
while left_ptr < len(left_part) and right_ptr<len(right_part):
if nums[left_part[left_ptr]]> nums[right_part[right_ptr]]:
ans.append(right_part[right_ptr])
right_ptr+=1
smaller_after+=1
else:
ans.append(left_part[left_ptr])
smaller[left_part[left_ptr]] += smaller_after
left_ptr+=1
temp = left_ptr
while temp < len(left_part):
smaller[left_part[temp]] += smaller_after
temp+=1
ans.extend(left_part[left_ptr:])
ans.extend(right_part[right_ptr:])
return ans
helper(0,len(nums)-1)
return smaller