leetcode 315. Count of Smaller Numbers After Self

本文探讨了解决“计数右侧更小元素”问题的两种方法。首先介绍了一种直观但效率较低的方法,使用map来统计每个元素右侧更小元素的数量;随后提出了一种改进方案,采用从右至左遍历数组的方式并利用lower_bound查找,显著提高了效率。

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

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


1、首先想到用map ,果断TLE。

class Solution {
public:
    vector<int> countSmaller(vector<int>& nums) 
    {
        map<int ,int> mp;
        for (auto i : nums)
            mp[i]++;
        vector<int> ret;
        for (auto i : nums)
        {
            mp[i] --;
            int count = 0;
            for (auto it = mp.begin(); it != mp.end(); it++)
            {
                if (it->first >= i)
                    break;
                count += it->second;
            }
            ret.push_back(count);
        }
        return ret;
    }
};

2、然后网上找了个方法

从右往左遍历数组,并且将搜索过的数有序的放到一个数组中,

然后每次从这个维护的数组中找到第一个大于当前元素的位置即可直到右边有多少个数比他小了.

这种方式的时间复杂度是O(n^2),因为数组插入元素的时间复杂度是O(n)(因为需要移位)


注意:

lower_bound( vector.begin(), vector.end(), value) 的用法 ,返回的也是迭代器。

vector.insert(迭代器,value) 的用法


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; 
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值