题目链接: https://leetcode.com/problems/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]
.
思路: 有两种思路可以做,第一种是从右往左遍历数组,并且将搜索过的数有序的放到一个数组中,然后每次从这个维护的数组中找到第一个大于当前元素的位置即可直到右边有多少个数比他小了.这种方式的时间复杂度是O(n^2),因为数组插入元素的时间复杂度是O(n)(因为需要移位).简单粗暴.虽然这种方法比朴素的O(n^2)有所优化, 但是本质上还是一样的, 我并不认为这个方法可以满足要求.
第二种方式是利用归并排序,其实就像是求逆序数一样.在将左右两半数组都排序之后,可以对左边数组中的每一个数在右边数组中找到有多少比他小的数.归并排序有很多额外的用途.这种方法的时间复杂度是O(nlog(n)).但是有点意外的是第一种效率比第二种还高一点,可能第二种的常量系数比较大吧.其实第二种还有一点可以优化,就是可以再用二分查找来找到第一个大于左边的数.但是不知道能优化多少.
代码如下:
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;
}
};
class Solution {
public:
void mergeSort(vector<pair<int, int>>& nums, int low, int high, vector<int> &ans)
{
if(low+1 == high) return;
int mid = (low+high)/2, right = mid;
mergeSort(nums, low, mid, ans);
mergeSort(nums, mid, high, ans);
for(int i = low; i < mid; i++)
{
while(right < high && nums[i].first > nums[right].first) right++;
ans[nums[i].second] += right-mid;
}
inplace_merge(nums.begin()+low, nums.begin()+mid, nums.begin()+right);
}
vector<int> countSmaller(vector<int>& nums) {
if(nums.size()==0) return {};
int len = nums.size();
vector<int> ans(len, 0);
vector<pair<int, int>> vec;
for(int i =0; i < len; i++) vec.push_back(make_pair(nums[i], i));
mergeSort(vec, 0, len, ans);
return ans;
}
};