-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path315.计算右侧小于当前元素的个数.cpp
91 lines (77 loc) · 1.77 KB
/
315.计算右侧小于当前元素的个数.cpp
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
/*
* @lc app=leetcode.cn id=315 lang=cpp
*
* [315] 计算右侧小于当前元素的个数
*/
// @lc code=start
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<int> c;
vector<int> a;
void Init(int length){
c.resize(length, 0);
}
int LowBit(int x){
return x & (-x);
}
void Update(int pos)
{
while(pos < c.size())
{
c[pos] += 1;
pos += LowBit(pos);
}
}
int Query(int pos)
{
int ret = 0;
while(pos>0){
ret += c[pos];
pos -= LowBit(pos);
}
return ret;
}
void Discretization(vector<int> &nums)
{
a.assign(nums.begin(), nums.end());
sort(a.begin(), a.end());
a.erase(unique(a.begin(),a.end()), a.end());
}
int getId(int x){
return lower_bound(a.begin(), a.end(), x) - a.begin() + 1;
}
vector<int> countSmaller(vector<int>& nums) {
vector<int> res;
Discretization(nums);
Init(nums.size()+5);
for(int i=nums.size()-1;i>=0;--i)
{
int id = getId(nums[i]);
res.push_back(Query(id-1));
Update(id);
}
reverse(res.begin(), res.end());
return res;
}
// vector<int> countSmaller(vector<int>& nums) {
// vector<int> counts(nums.size(), 0);
// for(int i=0;i<nums.size();i++)
// {
// int s = 0;
// for(int j=i+1;j<nums.size();j++)
// {
// if(nums[j] < nums[i])
// {
// s++;
// }
// }
// counts[i] = s;
// }
// return counts;
// }
};
// @lc code=end