[leetcode] 315. Count of Smaller Numbers After Self

本文介绍了一种解决LeetCode上“计数右侧更小元素”问题的有效算法。该问题要求对于给定数组中的每个元素,找出其右侧比它小的元素数量。文章详细解析了一种基于二分搜索的解决方案,通过逆序遍历并插入元素到已排序数组中,巧妙地计算出所需结果。

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

Description

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:

Input: [5,2,6,1]
Output: [2,1,1,0] 
Explanation:
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.

分析

题目的意思是:给你一个数组,然后求出数组中每个数,其右边比当前数小的个数,如果不明白的话,看一下Example就知道了。

  • 这是一道leetcode hard难度的题目,暴力破解肯定会有问题。
  • 首先可以使用用二分搜索法,思路是将给定数组从最后一个开始,用二分法插入到一个新的数组,这样新数组就是有序的,那么此时该数字在新数组中的坐标就是原数组中其右边所有较小数字的个数。
  • 思路很奇妙,我也做不出来,学习一下。

代码

class Solution {
public:
    vector<int> countSmaller(vector<int>& nums) {
        vector<int> res(nums.size(),0);
        vector<int> t;
        for(int i=nums.size()-1;i>=0;i--){
            int left=0;
            int right=t.size();
            while(left<right){
                int mid=(left+right)/2;
                if(nums[i]>t[mid]){
                    left=mid+1;
                }else{
                    right=mid;
                }
            }
            res[i]=right;
            t.insert(t.begin()+right,nums[i]);
        }
        return res;
    }
};

参考文献

[LeetCode] Count of Smaller Numbers After Self 计算后面较小数字的个数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值