275. H-Index II

Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?

s思路:
1. 排过序的,就更好办了!
2. 不对,肯定不是o(n)这么便宜的事。排序,又都是正数,还不得用binary search啊。绝了!
3. debug疑问:最后返回的时候是n-l还是n-r?
这里写图片描述
s这是千年老问题了,返回到底返回啥一定要根据问题来定,不能一概而论。比如这里,while运行到边界的时候,l==r==m,此时如果if(citations[m]>n-m),表示后面的长度比citations[m]小,那么取长度就可以了,即:n-m或n-l,注意不能取n-r,因为最后一步r=m-1;如果if(citations[m]

class Solution {
public:
    int hIndex(vector<int>& citations) {
        //
        int n=citations.size();
        if(n==0) return 0;
        int l=0,r=n-1;
        while(l<=r){
            int m=l+(r-l)/2;
            if(citations[m]==n-m) return citations[m];
            if(citations[m]>n-m)
                r=m-1;
            else
                l=m+1;    
        }
        return n-l;//bug:最后返回的时候是n-l还是n-r?
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值