原题链接在这里: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].

题解:

从右向左扫描数组nums, try to find the position of nums[i] in BST.

For each BST node, it contains its left subtree size count, its duplicate count.

When inserting a new node, returns the sum of smaller count.

Time Complexity: O(n^2). BST不一定balance. Space: O(n).

AC Java:

 class Solution {
public List<Integer> countSmaller(int[] nums) {
LinkedList<Integer> res = new LinkedList<>();
if(nums == null || nums.length == 0){
return res;
} int n = nums.length;
res.offerFirst(0);
TreeNode root = new TreeNode(nums[n - 1]);
root.count = 1; for(int i = n - 2; i >= 0; i--){
int smallerCount = insert(root, nums[i]);
res.offerFirst(smallerCount);
} return res;
} private int insert(TreeNode root, int num){
int smallerCountSum = 0;
while(root.val != num){
if(root.val > num){
root.leftCount++;
if(root.left == null){
root.left = new TreeNode(num);
} root = root.left;
}else{
smallerCountSum += root.leftCount + root.count;
if(root.right == null){
root.right = new TreeNode(num);
} root = root.right;
}
} root.count++;
return smallerCountSum + root.leftCount;
}
} class TreeNode{
int val;
int count;
int leftCount;
TreeNode left;
TreeNode right; public TreeNode(int val){
this.val = val;
this.count = 0;
this.leftCount = 0;
}
}

类似Reverse Pairs.

最新文章

  1. SharePreferences的DB实现
  2. 1019: [SHOI2008]汉诺塔
  3. ruby on rails 在centos 7下的安装配置
  4. fragment中嵌入viewpager的问题
  5. 在Myeclipse中配置Maven
  6. SQL统计——按照各种维度
  7. 大规模字符串检索-压缩trie树
  8. Python学习笔记:05类
  9. 实现android里面WebView显示内容
  10. 【USACO08NOV】奶牛混合起来Mixed Up Cows
  11. Pytorch入门实例:mnist分类训练
  12. VC禁止或允许拖拽改变窗口尺寸
  13. 迁移桌面程序到MS Store(3)——开机自启动
  14. Python将某文件夹及其子文件夹下某种格式的文件移动到另一个指定的文件下
  15. HDU - 1022 Train Problem I STL 压栈
  16. 第02章 查询DSL进阶
  17. ADF系列-2.EO的高级属性
  18. MyCat配置和使用
  19. Maven初步接触
  20. Linux minicom命令

热门文章

  1. 向 ViewPager 中添加 包含 ListView 的 Fragment
  2. Android 实用开源控件
  3. QtCreator下运行opencv出现realloc():pointer invalid
  4. ACM: HDU 3790 最短路径问题-Dijkstra算法
  5. 【BZOJ】2434: [Noi2011]阿狸的打字机
  6. 【HDU】1846 Brave Game
  7. POJ 1673 EXOCENTER OF A TRIANGLE(垂心)
  8. osg 路径 动画 效果
  9. KeyValue与KeyData与KeyCode区别(转)
  10. 第一次scrum meeting 报告