[Leetcode] 315. Count of Smaller Numbers After Self 解题报告

本文介绍了一种使用插入排序算法解决寻找数组中每个元素右侧较小元素数量的问题。通过逆序插入并利用lower_bound查找正确位置,该方法巧妙地解决了问题。尽管存在时间复杂度较高的缺点,但在特定场景下仍不失为一种实用方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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].

思路

这道题目虽然还有其它解法,但我觉得最巧妙的还是利用插入排序:我们将nums中数字以逆序的方式插入一个有序数组中。由于它插入的位置就是它的右边比它小的数字的个数,所以直接就可以采用lower_bound就获得其正确的插入位置。最后把结果数组逆序一下返回即可。不过不好的消息是:由于在vector中插入数字会导致里面的元素整体移动,最坏情况下该算法的时间复杂度高达O(n^2)。

我也尝试采用multiset数据结构来模拟插入排序,因为对于这个数据结构而言,lower_bound和insert的时间复杂度都是O(logn),但是在提交的时候竟然超时了。看来理论时间复杂度和实际运行的时间复杂度还是有差别的。

代码

class Solution {
public:
    vector<int> countSmaller(vector<int>& nums) {
        vector<int> sorted;
        vector<int> ret;
        if(nums.size() == 0) {
            return ret;
        }
        for(int i = nums.size() - 1; i >= 0; --i) {
            auto it = lower_bound(sorted.begin(), sorted.end(), nums[i]);
            ret.push_back(distance(sorted.begin(), it));
            sorted.insert(it, nums[i]);
        }
        reverse(ret.begin(), ret.end());
        return ret;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值