315. Count of Smaller Numbers After Self
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]
.
1、首先想到用map ,果断TLE。
class Solution {
public:
vector<int> countSmaller(vector<int>& nums)
{
map<int ,int> mp;
for (auto i : nums)
mp[i]++;
vector<int> ret;
for (auto i : nums)
{
mp[i] --;
int count = 0;
for (auto it = mp.begin(); it != mp.end(); it++)
{
if (it->first >= i)
break;
count += it->second;
}
ret.push_back(count);
}
return ret;
}
};
2、然后网上找了个方法
从右往左遍历数组,并且将搜索过的数有序的放到一个数组中,
然后每次从这个维护的数组中找到第一个大于当前元素的位置即可直到右边有多少个数比他小了.
这种方式的时间复杂度是O(n^2),因为数组插入元素的时间复杂度是O(n)(因为需要移位)
注意:
lower_bound( vector.begin(), vector.end(), value) 的用法 ,返回的也是迭代器。
vector.insert(迭代器,value) 的用法
class Solution {
public:
vector<int> countSmaller(vector<int>& nums)
{
vector<int> db;
vector<int> result(nums.size());
for(int i = nums.size()-1; i >= 0; i--)
{
auto it = lower_bound(db.begin(), db.end(), nums[i]);
result[i] = it - db.begin();
db.insert(it, nums[i]); //保证插入后有序
}
return result;
}
};