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

该博客详细介绍了LeetCode 315题的解题过程,主要讨论了两种解决方案:从右向左遍历数组并维护有序数组,以及使用归并排序来计算每个元素右侧更小的数的数量。虽然第一种方法时间复杂度为O(n^2),但实际效率高于第二种O(nlog(n))的归并排序方法,可能因为归并排序的常量系数较大。文章提供了相关的代码实现。

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

题目链接: 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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值