【Leetcode】Count of Smaller Numbers After Self

题目链接:https://leetcode.com/problems/count-of-smaller-numbers-after-self/

题目:

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

Example:

Given nums = [5, 2, 6, 1]

To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.

Return the array [2, 1, 1, 0].

思路:

建立一个二叉搜索树,在建树的过程中,记录在数组右边比自身小的元素个数。 算法复杂度O(nlogn),用动态规划复杂度为O(n^2)。

其中cnt为该结点相同大小元素的个数,用于重复元素判断。。。其实可以省略。。懒得改了

算法:

public List<Integer> countSmaller(int[] nums) {  
        List<Integer> list = new ArrayList<Integer>();  
        int res[] = new int[nums.length];  
        for (int i = nums.length - 1; i >= 0; i--) {  
            res[i] = insert(nums[i]);  
        }  
        for (int i : res) {  
            list.add(i);  
        }  
        return list;  
    }  
  
    TreeNode tRoot;  
  
    private Integer insert(int val) {  
        int cnt = 0;  
        if (tRoot == null) {  
            tRoot = new TreeNode(val);  
            return cnt;  
        }  
        TreeNode root = tRoot;  
        while (root != null) {  
            if (val < root.val) {  
                root.leftCnt++;  
                if (root.left == null) {  
                    root.left = new TreeNode(val);  
                    break;  
                } else  
                    root = root.left;  
            } else if (val > root.val) {  
                cnt += root.leftCnt + root.cnt;  
                if (root.right == null) {  
                    root.right = new TreeNode(val);  
                    break;  
                } else  
                    root = root.right;  
            } else {  
                cnt += root.leftCnt;  
                root.cnt++;  
                break;  
            }  
        }  
  
        return cnt;  
    }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值