leetcode315. 计算右侧小于当前元素的个数(树状数组解法)

leetcode315. 计算右侧小于当前元素的个数(树状数组解法)
题目:给定一个整数数组 nums,按要求返回一个新数组 counts。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。

树状数组解法


```java
class Solution {
    public List countSmaller(int[] nums) {

        ArrayList res=new ArrayList<>();
        int n=nums.length;
        if(n==0) return res;
        //利用二叉搜索树
        Set set=new TreeSet<>();
        for(int c:nums) set.add(c);
        //生成排名表
        int level=1;
        HashMap map=new HashMap<>();
        for(int c:set)
        {
            map.put(c,level);
            level++;
        }
        
        fenWickTree helper=new fenWickTree(set.size()+1);
        for(int i=n-1;i>=0;i--)
        {
            int temp=map.get(nums[i]);//当前元素的排名

            helper.update(temp,1);//将当前元素的名次更新数字数组

            res.add(helper.query(temp-1));//查询小于当前元素的
        }
        Collections.reverse(res);
        return res;
    }
    class fenWickTree//树状数组
    {
        int[] sum;
        int len;
        public fenWickTree(int n)
        {
            len=n;
            sum=new int[n+1];

        }
        public int lowBits(int x)
        {
            return x&(-x);
        }
        public void update(int i,int num)
        {

            while (i<=len)
            {
                sum[i]+=num;
                i+=lowBits(i);
            }

        }
        public int query(int i)
        {
            int res=0;
            while (i>0)
            {
                res+=sum[i];
                i-=lowBits(i);

            }
          return res;
        }

        
        
    }
}

你可能感兴趣的:(leetcode,leetcode,数据结构,算法)