[LeetCode] 315
来源:互联网 发布:利用广告联盟做淘宝客 编辑:程序博客网 时间:2024/05/16 09:16
315. Count of Smaller Numbers After Self
题目:给定一个数列,返回vector<int> count, count[i] 代表 nums 中在nums[i] 之后且比nums[i] 小的数字的个数
思路:建立BST,每个节点除了左右child之外增加一个int l代表数组中比l小的数的数量。
从后往前遍历数组,把每个数字插入BST的时候统计比它小的数字的个数
如果root->val >= a, 那么插入左子树,root->l++
如果root->val < a, 那么插入右子树,ans += root->l
当数字被插入时返回ans的数字
struct Node{ Node* left; Node* right; int val; int l; Node(int x) : val(x), left(NULL), right(NULL), l(0) {}}; void insert(Node* & root, int a , int & ans){ if(root == NULL) { root = new Node(a); return; } if(root->val >= a) { root->l++; insert(root->left, a, ans); } else { ans += root->l+1; insert(root->right, a, ans); }}vector<int> countSmaller(vector<int> &nums){ int n = nums.size(); if(n == 0) return vector<int>(); vector<int> result(nums.size(), 0); Node* root = new Node(nums[n-1]); for(int i = n-2; i >= 0; i--) { int ans = 0; insert(root, nums[i] , ans); result[i] = ans; } return result;}
0 0
- [LeetCode] 315
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- SpringMvc和Struts2的区别
- Leetcode 250Count Univalue Subtrees
- Context initialization failed
- 【Java SE】————如何做到跨平台性的?
- C/C++log日志库比较
- [LeetCode] 315
- xcode 下载更新地址
- Poisson image editing算法实现的Matlab代码解析
- Java常见错误汇总
- Oracle与Tomcat端口冲突,报错:Protocol handler initialization failed;Socket bind failed
- USACO Your Ride Is Here 解题日志
- UniCode 下 CString 转 char* 的方法
- Julia: 趣!,13579分别在一本168页书的页码中出现的次数
- hdu(1171)——Big Event in HDU