LeetCode 315.Count of Smaller Numbers After Self
来源:互联网 发布:sftp 修改端口号 编辑:程序博客网 时间:2024/06/06 14:03
题目
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:
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].
难易度:Hard
思路
这道题是要求数出数组中每个数字后面比它小的数有几个,然后返回一个新的数组存放这些个数。最直接的方法就是一个一个的遍历,这样复杂度要O(n^2)。所以用另外一个思路,利用二分排序,将数组从最后一个插入到一个新的数组中,这样每个数字插入的位置的序号就是后面比它小的元素的个数。
代码
class Solution {public: vector<int> countSmaller(vector<int>& nums) { int n = nums.size(); vector<int> arr,count(n); for(int i = n-1; i >= 0; --i ) { int left = 0; int right = arr.size(); while(left < right){ int mid = left+(right-left)/2; if(nums[i] <= arr[mid]) { right = mid; } else { left = mid+1; } } count[i] = right; arr.insert(arr.begin()+right, nums[i]); } return count; }};
注:
1. vector.insert(vector.begin()+i,a); 在vector第i个元素后插入a
2. 在进行二分排序时,注意边界值的判断和选择
0 0
- leetcode Count of Smaller Numbers After Self
- leetcode Count of Smaller Numbers After Self
- leetcode Count of Smaller Numbers After Self
- Count of Smaller Numbers After Self | LeetCode
- leetcode Count of Smaller Numbers After Self
- LeetCode Count of Smaller Numbers After Self
- [Leetcode]Count of Smaller Numbers After Self
- leetcode - Count of Smaller Numbers After Self
- leetcode:Count of Smaller Numbers After Self
- 【Leetcode】Count of Smaller Numbers After Self
- 【leetCode】 Count of Smaller Numbers After Self
- [Leetcode] Count of Smaller Numbers After Self
- LeetCode -- Count of Smaller Numbers After Self
- Leetcode Count of Smaller Numbers After Self
- LeetCode -- Count of Smaller Numbers After Self
- LeetCode-Count of Smaller Numbers After Self
- [leetcode] 315. Count of Smaller Numbers After Self 解题报告
- LeetCode 315. Count of Smaller Numbers After Self
- 1008. Elevator (20)
- Spring 框架的设计理念与设计模式分析
- 算法w2——Regular Expression Matching(leetcode 10)
- s5pv210开发板笔记
- 安卓自定义View
- LeetCode 315.Count of Smaller Numbers After Self
- Java设计模式-单类模式
- Spring MVC开发实现步骤
- HDU 6011 Lotus and Characters【思维】【pair】
- 第63篇一对多之学生端修改私有白板并保存(二)
- JDK,JRE,JVM的作用及关系
- 【前端】meta标签
- git,sourcetree和bitbucket的使用教程
- Quartz学习笔记(三)—— TriggerListeners and JobListeners