leetcode315
public class Solution {
public List<Integer> countSmaller(int[] nums) {
List<Integer> res = new ArrayList<>();
if(nums == null || nums.length == 0) return res;
TreeNode root = new TreeNode(nums[nums.length - 1]);
res.add(0);
for(int i = nums.length - 2; i >= 0; i--) {
int count = insertNode(root, nums[i]);
res.add(count);
}
Collections.reverse(res);
return res;
}
public int insertNode(TreeNode root, int val) {
int thisCount = 0;
while(true) {
if(val <= root.val) {
root.count++;
if(root.left == null) {
root.left = new TreeNode(val); break;
} else {
root = root.left;
}
} else {
thisCount += root.count;
if(root.right == null) {
root.right = new TreeNode(val); break;
} else {
root = root.right;
}
}
}
return thisCount;
}
}
class TreeNode {
TreeNode left;
TreeNode right;
int val;
int count = 1;
public TreeNode(int val) {
this.val = val;
}
}
从后向前进行判断,线性的搜索时间复杂度比较高,因此建立一个二叉搜索树,每次插入节点的时候,更新父节点的“右侧小”的数字的数量。
leetcode315的更多相关文章
- LeetCode315—Count of Smaller Numbers After Self—Java版归并算法
这是我在研究leetcode的solution第一个解决算法时,自己做出的理解,并且为了大家能看懂,做出了详细的注释. 此算法算是剑指Offer36的升级版,都使用的归并算法,但是此处的算法,难度更高 ...
- [Swift]LeetCode315. 计算右侧小于当前元素的个数 | Count of Smaller Numbers After Self
You are given an integer array nums and you have to return a new countsarray. The counts array has t ...
- leetcode315 Count of Smaller Numbers After Self
思路: bit + 离散化. 实现: #include <bits/stdc++.h> using namespace std; class Solution { public: int ...
- leetcode315 计算右侧小于当前元素的个数
1. 采用归并排序计算逆序数组对的方法来计算右侧更小的元素 time O(nlogn): 计算逆序对可以采用两种思路: a. 在左有序数组元素出列时计算右侧比该元素小的数字的数目为 cnt=r-mid ...
- 第十四周 Leetcode 315. Count of Smaller Numbers After Self(HARD) 主席树
Leetcode315 题意很简单,给定一个序列,求每一个数的右边有多少小于它的数. O(n^2)的算法是显而易见的. 用普通的线段树可以优化到O(nlogn) 我们可以直接套用主席树的模板. 主席树 ...
随机推荐
- git 对比两个分支差异
比如我们有 2 个分支:master, dev,现在想查看这两个 branch 的区别,有以下几种方式: 1.查看 dev 有,而 master 中没有的: git log dev ^master 同 ...
- Office 2016 Pro Plus \ Project 专业版 \ Visio 专业版 \ 64 位vol版本方便KMS小马oem
在使用上,零售版和批量授权版并没有区别,只是授权方式方面的区别,相对而言,VOL 版的更容易激活一些,其他并没有什么区别了. 有需要的可以在下面下载:(以下均是 64位VL 版) 版本:Office ...
- JavaScript之图片操作5
本次的图片操作是要实现模仿天猫淘宝的放大镜效果,如下图所示: 其实现原理其实很简单,主要就是定位的运用,在上面的图中,左边是一个div,它的大小就是左边图片的大小,我们称为左窗口(原图),红色部分我们 ...
- random 产生一个随机数的方法
import random print( random.randint(1,10) ) # 产生 1 到 10 的一个整数型随机数 print( random.random() ) # 产生 0 到 ...
- dropwizard使用cors支持跨域浏览器取不到自定义header问题
dropwizard支持cors的配置如下: public void run(Configuration conf, Environment environment) { // Enable CORS ...
- Python中循环引用(import)失败的解决方法
原文链接:http://blog.ihuxu.com/the-solution-to-the-problem-of-circular-import-in-python/ 我是采用方案三 "将 ...
- header头参数不能带下划线
header头参数不能带下划线:game_id是错误的
- 必须熟练掌握的150个Linux命令
- Spark2.0.0源码编译
Hive默认使用MapReduce作为执行引擎,即Hive on mr,Hive还可以使用Tez和Spark作为其执行引擎,分别为Hive on Tez和Hive on Spark.由于MapRedu ...
- Github上关于iOS的各种开源项目集合2(强烈建议大家收藏,查看,总有一款你需要)
资源list:Github上关于大数据的开源项目.论文等合集 Awesome Big Data A curated list of awesome big data frameworks, resou ...