Skip to content

Commit b38dabe

Browse files
committed
count_of_smaller_numbers_after_self
1 parent 473bb11 commit b38dabe

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
228228
#### [309. Best Time to Buy and Sell Stock with Cooldown](https://github.com/hitzzc/go-leetcode/tree/master/best_time_to_buy_and_sell_stock_with_cooldown)
229229
#### [312. Burst Balloons](https://github.com/hitzzc/go-leetcode/tree/master/burst_balloons)
230230
#### [313. Super Ugly Number](https://github.com/hitzzc/go-leetcode/tree/master/super_ugly_number)
231+
#### [315. Count of Smaller Numbers After Self](https://github.com/hitzzc/go-leetcode/tree/master/count_of_smaller_numbers_after_self)
231232

232233

233234

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class binary_index_tree {
2+
vector<int> array;
3+
public:
4+
binary_index_tree(int n): array(n+1, 0) {}
5+
int lowbit(int x) {
6+
return x & (-x);
7+
}
8+
int sum(int idx) {
9+
int ret = 0;
10+
while (idx > 0) {
11+
ret += array[idx];
12+
idx -= lowbit(idx);
13+
}
14+
return ret;
15+
}
16+
void add(int idx, int val) {
17+
while (idx < array.size()) {
18+
array[idx] += val;
19+
idx += lowbit(idx);
20+
}
21+
}
22+
};
23+
24+
class Solution {
25+
public:
26+
vector<int> countSmaller(vector<int>& nums) {
27+
vector<int> sorted = nums;
28+
sort(sorted.begin(), sorted.end());
29+
unordered_map<int, int> mapping;
30+
for (int i = 0; i < sorted.size(); ++i) {
31+
mapping[sorted[i]] = i+1;
32+
}
33+
binary_index_tree my_bit(nums.size());
34+
vector<int> ret(nums.size());
35+
for (int i = nums.size()-1; i >=0; --i) {
36+
ret[i] = my_bit.sum(mapping[nums[i]]-1);
37+
my_bit.add(mapping[nums[i]], 1);
38+
}
39+
return ret;
40+
}
41+
};

0 commit comments

Comments
 (0)