给你一个整数数组 nums ,按要求返回一个新数组 counts 。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。
示例 1:
输入:nums = [5,2,6,1]
输出:[2,1,1,0]
解释:
5 的右侧有 2 个更小的元素 (2 和 1)
2 的右侧仅有 1 个更小的元素 (1)
6 的右侧有 1 个更小的元素 (1)
1 的右侧有 0 个更小的元素
示例 2:
输入:nums = [-1]
输出:[0]
示例 3:
输入:nums = [-1,-1]
输出:[0,0]
提示:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
解题思路:通过归并排序计算
代码如下:
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
int n = nums.size();
vector<int>res(n, 0);
vector<pair<int, int>> nnums(n);
for (int i = 0; i < n; ++i) nnums[i] = make_pair(nums[i], i);
helper(nnums, 0, n, res);
return res;
}
void helper(vector<pair<int, int>>&nums, int left , int right, vector<int>& res) {
if (right - left <= 1) return;
int mid = left + (right - left) / 2;
helper(nums, left, mid, res);
helper(nums, mid, right, res);
vector<pair<int, int>>cache(right - left);
int i = left, j = mid, k = 0;
while (i < mid && j < right) {
if (nums[i].first > nums[j].first) {
cache[k++] = nums[j++];
} else {
res[nums[i].second] += (j - mid);
cache[k++] = nums[i++];
}
}
while( i != mid) {
res[nums[i].second] += (right - mid);
cache[k++] = nums[i++];
}
while(j != right) cache[k++] = nums[j++];
for (int pos = 0; pos < cache.size(); ++pos) {
nums[left + pos] = cache[pos];
}
}
//两个栈
//归并排序,merge的时候计算
};