You are given an integer array nums and you have to return a new counts array. Thecounts 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].

Subscribe to see which companies asked this question

因为需要求某元素右边小于该元素的数组元素的个数,所以从数组末尾开始向前进行处理。数据结构使用树,节点有属性value,smaller,分别表示对应元素的值以及数组中小于该元素值的个数。函数insert既向树种插入新的节点,又能够求得数组右边小于value的元素的个数。因为数组末尾的元素的smaller值首先返回,所以要用到双向队列deque,将每次求得的值插入链表的头部。最终返回整个队列的值即可。

在插入操作中,请注意函数的参数root是指针的引用,因为对该指针的修改必须得到保留。如果root为空(代表数组末尾的那个元素),初始化根节点,返回0.如果根节点的值大于value,需要把这个元素对应的几点向左插入树中,同时,小于根节点的值的元素个数加1.剩余的情况下,节点需要向右插入树中,返回的值应该是比root节点小的元素个数加上树的右半部分比该元素小的元素个数,同时还要区分一下要插入的值是大于还是等于root节点的值。

很精妙的解法,真是只可意会,不可言传啊。

class Solution {
private:
class Node{
public:
int value;
int smaller;
Node *left;
Node *right;
Node(int value,int smaller) {
this ->value = value;
this ->smaller =smaller;
left=right=NULL;//在leetcode中,必须要加上这句,否则超时
}
};
int insert(Node * & root,int value){
if(root ==NULL){
root =new Node(value,);
return ;
}
if(root->value > value){
root->smaller++;
return insert(root->left,value);
}
return root->smaller+insert(root->right,value)+(root->value <value? :);
}
public:
vector<int> countSmaller(vector<int>& nums) {
Node * root=NULL;
deque <int >q;
for(int i=nums.size()-;i>-;i-- ){
int value =insert(root,nums[i]);
cout<<"this is a test! "<<value<<endl;
q.push_front(value);
}
return vector<int>(q.begin(),q.end());
}
};

最新文章

  1. jQuery系列:选择器
  2. Hibernate之lazy延迟加载
  3. maven install Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.1.1:war (default-war) on project web_nanchang
  4. iOS计算字符串的宽度高度
  5. python学习笔记 class
  6. java.util.regx Demo
  7. Construct Binary Tree from Preorder and Inorder Traversal——LeetCode
  8. Python之基础(一)
  9. windows环境下nutch2.x 在eclipse中实现抓取数据存进mysql详细步骤
  10. Mysql SlowLog 工具 pt-query-diglist
  11. ThinPHP第二十八天(F函数和file_put_contents区别|PHP生成PHP文件,Kindeditor编辑器使用方法)
  12. Android显示GIF动画完整示例(二)
  13. hdu4223(dp)
  14. 开源的JavaScript插件化框架MinimaJS
  15. PAT 1003. Emergency (25) dij+增加点权数组和最短路径个数数组
  16. 开发一个http代理服务器
  17. linux,shell脚本set -x的意思
  18. cmd命令中运行pytest命令导入模块报错解决方法
  19. js常用正则表达式判断
  20. JVM内存问题分析

热门文章

  1. linux logrotate配置
  2. linux性能优化cpu 磁盘IO MEM
  3. Android, BaseAdapter 处理大数据量时的优化
  4. hibernate中SQLQuery的addEntity()方法
  5. Hibernate的generator属性
  6. 基于I2C EPPRPM(AT24C02B) + LCD12864实验
  7. photosho 等距复制或旋转复制
  8. iOS之Alcatraz常见插件
  9. copy-on-write学习
  10. Git GitHub的使用