forked from garvit-bhardwaj/Leetcode-Problems-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountOfSmallerNumbersAfterSelf.cpp
More file actions
50 lines (41 loc) · 960 Bytes
/
CountOfSmallerNumbersAfterSelf.cpp
File metadata and controls
50 lines (41 loc) · 960 Bytes
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
class Solution {
public:
vector<int> bit;
void update(int x, int val, int m)
{
for(; x<=m; x+=(x&-x))
bit[x]+=val;
}
int getsum(int x)
{
int sum=0;
for(;x>0; x-=(x&-x))
sum += bit[x];
return sum;
}
vector<int> countSmaller(vector<int>& nums) {
bit.resize(200009);
int n = nums.size(), i;
map<int,int> mp;
for(i=0;i<n;i++)
{
mp[nums[i]]++;
}
int cnt=1;
for(auto itr=mp.begin(); itr!=mp.end(); itr++)
{
itr->second = cnt++;
}
for(i=0;i<n;i++)
{
nums[i] = mp[nums[i]];
}
vector<int> ans(n);
for(int i=n-1;i>=0;i--)
{
ans[i] = getsum(nums[i]-1);
update(nums[i], 1, 200007);
}
return ans;
}
};