LeetCode 315. Count of Smaller Numbers After Self(线段树,树状数组)
Posted Shendu.cc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 315. Count of Smaller Numbers After Self(线段树,树状数组)相关的知识,希望对你有一定的参考价值。
题意:找到数组里每个元素的右边有多少个元素小于当前元素
题解:单点更新,区间查询。线段树或者树状数组都可以。注意要离散化
class Solution {
public:
int c[100005];
int n;
map<int,int> m;
vector<int> countSmaller(vector<int>& nums) {
vector<int> a = nums;
sort(a.begin(),a.end());
for(int i=0;i<a.size();i++)
{
m[a[i]]=i+1;
}
n=nums.size();
vector<int> ans;
for(int i=n-1;i>=0;i--)
{
ans.push_back(sum(m[nums[i]]-1));
update(m[nums[i]]);
}
reverse(ans.begin(),ans.end());
return ans;
}
int lowbit(int x)
{
return x&(-x);
}
void update(int pos)
{
while(pos<=n)
{
c[pos]++;
pos+=lowbit(pos);
}
}
int sum(int pos)
{
int ans=0;
while(pos>0)
{
ans+=c[pos];
pos-=lowbit(pos);
}
return ans;
}
};
以上是关于LeetCode 315. Count of Smaller Numbers After Self(线段树,树状数组)的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 315. Count of Smaller Numbers After Self
leetcode No315. Count of Smaller Numbers After Self
leetcode No315. Count of Smaller Numbers After Self
leetcode No315. Count of Smaller Numbers After Self