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

Example:

  1. Input: [5,2,6,1]
  2. Output: [2,1,1,0]
  3. Explanation:
  4. To the right of 5 there are 2 smaller elements (2 and 1).
  5. To the right of 2 there is only 1 smaller element (1).
  6. To the right of 6 there is 1 smaller element (1).
  7. To the right of 1 there is 0 smaller element.

这道题给定了一个数组,让我们计算每个数字右边所有小于这个数字的个数,目测不能用 brute force,OJ 肯定不答应,那么为了提高运算效率,首先可以使用用二分搜索法,思路是将给定数组从最后一个开始,用二分法插入到一个新的数组,这样新数组就是有序的,那么此时该数字在新数组中的坐标就是原数组中其右边所有较小数字的个数,参见代码如下:

解法一:

  1. // Binary Search
  2. class Solution {
  3. public:
  4. vector<int> countSmaller(vector<int>& nums) {
  5. vector<int> t, res(nums.size());
  6. for (int i = nums.size() - ; i >= ; --i) {
  7. int left = , right = t.size();
  8. while (left < right) {
  9. int mid = left + (right - left) / ;
  10. if (t[mid] >= nums[i]) right = mid;
  11. else left = mid + ;
  12. }
  13. res[i] = right;
  14. t.insert(t.begin() + right, nums[i]);
  15. }
  16. return res;
  17. }
  18. };

上面使用二分搜索法是一种插入排序的做法,我们还可以用 C++ 中的 STL 的一些自带的函数,比如求距离 distance,或是求第一个不小于当前数字的函数 lower_bound(),这里利用这两个函数代替了上一种方法中的二分搜索的部分,两种方法的核心思想都是相同的,构造有序数组,找出新加进来的数组在有序数组中对应的位置存入结果中即可,参见代码如下:

解法二:

  1. // Insert Sort
  2. class Solution {
  3. public:
  4. vector<int> countSmaller(vector<int>& nums) {
  5. vector<int> t, res(nums.size());
  6. for (int i = nums.size() - ; i >= ; --i) {
  7. int d = distance(t.begin(), lower_bound(t.begin(), t.end(), nums[i]));
  8. res[i] = d;
  9. t.insert(t.begin() + d, nums[i]);
  10. }
  11. return res;
  12. }
  13. };
再来看一种利用二分搜索树来解的方法,构造一棵二分搜索树,稍有不同的地方是需要加一个变量 smaller 来记录比当前结点值小的所有结点的个数,每插入一个结点,会判断其和根结点的大小,如果新的结点值小于根结点值,则其会插入到左子树中,此时要增加根结点的 smaller,并继续递归调用左子结点的 insert。如果结点值大于根结点值,则需要递归调用右子结点的 insert 并加上根结点的 smaller,并加1,参见代码如下:
解法三:
  1. // Binary Search Tree
  2. class Solution {
  3. public:
  4. struct Node {
  5. int val, smaller;
  6. Node *left, *right;
  7. Node(int v, int s) : val(v), smaller(s), left(NULL), right(NULL) {}
  8. };
  9. int insert(Node*& root, int val) {
  10. if (!root) return (root = new Node(val, )), ;
  11. if (root->val > val) return root->smaller++, insert(root->left, val);
  12. return insert(root->right, val) + root->smaller + (root->val < val ? : );
  13. }
  14. vector<int> countSmaller(vector<int>& nums) {
  15. vector<int> res(nums.size());
  16. Node *root = NULL;
  17. for (int i = nums.size() - ; i >= ; --i) {
  18. res[i] = insert(root, nums[i]);
  19. }
  20. return res;
  21. }
  22. };

Github 同步地址:

https://github.com/grandyang/leetcode/issues/315

类似题目:

Count of Range Sum

Queue Reconstruction by Height

Reverse Pairs

参考资料:

https://leetcode.com/problems/count-of-smaller-numbers-after-self/

https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/76576/My-simple-AC-Java-Binary-Search-code

https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/138154/The-C%2B%2B-merge-sort-template-for-pairs-'i'-'j'-problem

https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/76611/Short-Java-Binary-Index-Tree-BEAT-97.33-With-Detailed-Explanation

https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/76657/3-ways-(Segment-Tree-Binary-Indexed-Tree-Binary-Search-Tree)-clean-python-code

https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/76607/C%2B%2B-O(nlogn)-Time-O(n)-Space-MergeSort-Solution-with-Detail-Explanation

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Count of Smaller Numbers After Self 计算后面较小数字的个数的更多相关文章

  1. [LeetCode] 315. Count of Smaller Numbers After Self 计算后面较小数字的个数

    You are given an integer array nums and you have to return a new counts array. The countsarray has t ...

  2. 315 Count of Smaller Numbers After Self 计算右侧小于当前元素的个数

    给定一个整型数组 nums,按要求返回一个新的 counts 数组.数组 counts 有该性质: counts[i] 的值是  nums[i] 右侧小于nums[i] 的元素的数量.例子:给定 nu ...

  3. LeetCode Count of Smaller Numbers After Self

    原题链接在这里:https://leetcode.com/problems/count-of-smaller-numbers-after-self/ 题目: You are given an inte ...

  4. leetcode 315. Count of Smaller Numbers After Self 两种思路(欢迎探讨更优解法)

    说来惭愧,已经四个月没有切 leetcode 上的题目了. 虽然工作中很少(几乎)没有用到什么高级算法,数据结构,但是我一直坚信 "任何语言都会过时,只有数据结构和算法才能永恒". ...

  5. leetcode 315. Count of Smaller Numbers After Self 两种思路

    说来惭愧,已经四个月没有切 leetcode 上的题目了. 虽然工作中很少(几乎)没有用到什么高级算法,数据结构,但是我一直坚信 "任何语言都会过时,只有数据结构和算法才能永恒". ...

  6. [LeetCode] 315. Count of Smaller Numbers After Self (Hard)

    315. Count of Smaller Numbers After Self class Solution { public: vector<int> countSmaller(vec ...

  7. [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 ...

  8. LeetCode "Count of Smaller Number After Self"

    Almost identical to LintCode "Count of Smaller Number before Self". Corner case needs to b ...

  9. 315.Count of Smaller Numbers After Self My Submissions Question

    You are given an integer array nums and you have to return a new counts array. Thecounts array has t ...

随机推荐

  1. PL/sql使用总结

    ①右键表拖入到sql窗口中,可自动生成脚本: ②可以和Excel直接复制粘贴: ③F5查看执行计划: ④有环境变量则用环境变量,否则就会去注册表中找对应的值 ⑤oracle客户端设置编码只是为了告诉数 ...

  2. 【转】linux内核中writesb(), writesw(), writesl() 宏函数

    writesb(), writesw(), writesl() 宏函数 功能 : writesb()    I/O 上写入 8 位数据流数据 (1字节) writesw()   I/O  上写入 16 ...

  3. C语言用分别用递归和循环求数字的阶乘的方法

    以下代码均为 自己 实现,嘻嘻! 参考文章:http://blog.csdn.net/talk_8/article/details/46289683 循环法 int CalFactorial(int ...

  4. spring mvc 和spring security配置 web.xml设置

    <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmln ...

  5. JDBC_part2_DML以及预编译_编写DBUtil工具类

    本文为博主辛苦总结,希望自己以后返回来看的时候理解更深刻,也希望可以起到帮助初学者的作用. 转载请注明 出自 : luogg的博客园 谢谢配合! jdbc day02 DML语法 比起插叙语句,没有R ...

  6. python学习笔记(python简史)

    一.python介绍 python的创始人为吉多·范罗苏姆(Guido van Rossum) 目前python主要应用领域: ·云计算 ·WEB开发 ·科学运算.人工智能 ·系统运维 ·金融:量化交 ...

  7. jdk jre jvm 三者之间关系

    JDK JDK是java开发工具包,是Sun公司针对Java开发员的产品.     JDK 中包含JRE,在JDK安装的目录下有一个叫jre的目录,里面有两个文件夹,bin/和lib,其中bin就是j ...

  8. 【H5疑难杂症】脱离文档流时的渲染BUG

    BUG重现 最近机票团队在一个页面布局复杂的地方发现一个BUG,非常奇怪并且不好定位,这类问题一般最后都会到我这里,这个问题是,改变dom结构,页面却不渲染!!! 如图所示,我动态的改变了dom结构, ...

  9. [tableView reloadData] 和 runloop

    需要[tableView reloadData]后需要立即获取tableview的cell.高度,或者需要滚动tableview,那么,直接在reloadData后执行代码是会有问题的. 断点调试感觉 ...

  10. IOS之Objective-C学习 代理设计模式

    鉴于Objective-C是不支持多继承的,所以需要用协议来代替实现其他类的方法,所以有了代理设计模式. 代理,又称委托,delegation. 代理模式可以让一个单继承的类实现父类以外其他类的方法. ...