315. 计算右侧小于当前元素的个数 - 力扣(LeetCode)
暴力法,两层for循环,很简单,但是会超出时间限制。怎么优化呢?
借助辅助数组可以将右边的元素边处理边添加(添加的同时保持有序):
逆序遍历+插入排序的思路:
性能比较一般,应该是vector插入操作需要移动元素,所以比较耗时。
class Solution {
public:
vector<int> help;
vector<int> countSmaller(vector<int>& nums) {
int n = nums.size();
if(n == 0) return vector<int>();
vector<int> res(n, 0);
for(int i = n-1; i >= 0; --i){//插入排序的思路
auto it = lower_bound(help.begin(), help.end(), nums[i]);
res[i] = it - help.begin();
help.insert(it, nums[i]);
}
return res;
}
};
归并排序
和这个类似剑指 Offer 51. 数组中的逆序对_qq_32523711的博客-CSDN博客
归并排序简直就是为这题量身定制的。
左右两个都是有序的集合合并,所以可以在合并的过程中计算左边的每个元素在它的右边有多少小于它的元素,归并排序的过程和计算某个元素右边有多少个小于它的元素这个过程完美契合
class Solution {
public:
vector<int> res;
vector<pair<int, int>> copy_nums;
vector<pair<int, int>> tmp;
void merge(vector<pair<int, int>> ©_nums, int l, int mid, int r){
int i = l, j = mid+1, k = 0;
while(i <= mid && j <= r){
if(copy_nums[i].first <= copy_nums[j].first){
tmp[k++] = copy_nums[i];
res[copy_nums[i++].second] += j - mid-1;
}else tmp[k++] = copy_nums[j++];
}
while(i <= mid){
tmp[k++] = copy_nums[i];
res[copy_nums[i++].second] += r-mid;//所有元素均比它小
}
while(j <= r) tmp[k++] = copy_nums[j++];
copy(tmp.begin(), tmp.begin()+k, copy_nums.begin()+l);
}
void merge_sort(vector<pair<int, int>> ©_nums, int l, int r){//参数一定要用引用
if(l >= r) return;//只有一个元素
int mid = l + (r - l) /2;
merge_sort(copy_nums, l, mid);
merge_sort(copy_nums, mid+1, r);
if(copy_nums[mid].first <= copy_nums[mid+1].first) return;//提前终止
merge(copy_nums, l, mid, r);
}
vector<int> countSmaller(vector<int>& nums) {
int n = nums.size();
if(n == 0) return res;
for(int i = 0; i < n; ++i) copy_nums.push_back({nums[i], i});
tmp.resize(n);
res.resize(n);
//使用pair的原因是需要随时记录该值在nums中的索引,因为归并排序后值的位置就改变了
//但是返回的res需要原始的索引信息
merge_sort(copy_nums, 0, n-1);
return res;
}
};