LeetCode Count of Smaller Numbers After Self
2024-10-15 00:41:45
原题链接在这里: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;
}
}
最新文章
- SharePreferences的DB实现
- 1019: [SHOI2008]汉诺塔
- ruby on rails 在centos 7下的安装配置
- fragment中嵌入viewpager的问题
- 在Myeclipse中配置Maven
- SQL统计——按照各种维度
- 大规模字符串检索-压缩trie树
- Python学习笔记:05类
- 实现android里面WebView显示内容
- 【USACO08NOV】奶牛混合起来Mixed Up Cows
- Pytorch入门实例:mnist分类训练
- VC禁止或允许拖拽改变窗口尺寸
- 迁移桌面程序到MS Store(3)——开机自启动
- Python将某文件夹及其子文件夹下某种格式的文件移动到另一个指定的文件下
- HDU - 1022 Train Problem I STL 压栈
- 第02章 查询DSL进阶
- ADF系列-2.EO的高级属性
- MyCat配置和使用
- Maven初步接触
- Linux minicom命令
热门文章
- 向 ViewPager 中添加 包含 ListView 的 Fragment
- Android 实用开源控件
- QtCreator下运行opencv出现realloc():pointer invalid
- ACM: HDU 3790 最短路径问题-Dijkstra算法
- 【BZOJ】2434: [Noi2011]阿狸的打字机
- 【HDU】1846 Brave Game
- POJ 1673 EXOCENTER OF A TRIANGLE(垂心)
- osg 路径 动画 效果
- KeyValue与KeyData与KeyCode区别(转)
- 第一次scrum meeting 报告