标签:upper lower smaller val nums int bound right
LeetCode 315. 计算右侧小于当前元素的个数
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 1:
Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation:
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.
Constraints:
- 0 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
解题思路
- 使用二分查找优化的插入排序
- 二叉搜索树
- 归并排序
- 树状数组
- 线段树
参考代码
/*
* @lc app=leetcode id=315 lang=cpp
*
* [315] Count of Smaller Numbers After Self
*/
// @lc code=start
class Solution {
public:
// Insertion Sort with binary search optimization
vector<int> countSmaller(vector<int>& nums) {
if (nums.empty()) return {};
size_t n = nums.size();
vector<int> res(n);
res[n-1] = 0;
for (int i=n-2; i>=0; i--) {
// find the 1st elements less than val
int val = nums[i];
int l = i+1, r = n;
while (l < r) {
int m = l + (r - l) / 2;
if (nums[m] >= val) {
l = m + 1;
} else {
r = m;
}
} // upper_bound in descending array
// return l;
for (int j = i; j + 1 < l; j++) {
nums[j] = nums[j+1];
}
nums[l-1] = val;
res[i] = n-l;
}
return res;
} // AC, runtime beats 5.07 % of cpp submissions
};
// @lc code=end
注意:使用开区间,这样区间只有两个元素的时候选择的mid是第二个元素,避免了nums[m] < val
时更新r = m
的死循环。
upper_bound 和 lower_bound 的实现参考:
标签:upper,lower,smaller,val,nums,int,bound,right 来源: https://www.cnblogs.com/zhcpku/p/14318805.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。