zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    SSH异常
    jquery效果摘要
    js随笔
    html随笔
    demo小样
    SVG图标
    jQuery笔记
    html / css学习笔记-3
    angular 学习笔记
    ng-route使用笔记
  • 原文地址:https://www.cnblogs.com/dacc123/p/12488667.html
Copyright © 2011-2022 走看看