274. H 指数 ---二分法记录

在这里插入图片描述

在这里插入图片描述

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int l = 0, r = citations.size()+1; //至于为什么要加1呢,我们要保证第一次的r不是我们要的那就是+1呗~~让他大!!!
        while (l < r) {
            int mid = (l+r)/2;
            int cnt = 0;
            for (int& i : citations) {
                if (i >= mid) {
                    cnt ++;
                }
            }
            if (cnt < mid) {
                r = mid; //因为在这里mid太大了 本来应该r=mid-1,我们还是保留了。而下面的left可能导致l=r,此时r不是我们要的所以l要减少1呢
            } else {
                l = mid + 1;//因为我要寻找最大的L是多少,
            }
        }
        return l - 1;
    }
};

另一种二分查找,考虑到还是想保持逻辑运算的规则,但是这边逻辑运算的话 r是必须减少,我们要找到最大的一个符合条件得值,我们担心 l 和 r相差一个单位的时候,陷入死循环,mid=l,而且也是走下面的道路,怎么办?那就是l+r+1这样能帮助我们把mid拉到right地方!

class Solution {
public:
    int hIndex(vector<int>& cit) {
        int n=cit.size();
        int l = 0, r = n;
        while(l < r){
            int mid = (l+r+1)/2;  //+1是为了避免当n=1时,程序陷入死循环
            int t = 0;
            for(auto x:cit){
                if(x >= mid) t ++;
            }
            if(t < mid) r = mid - 1;  //此时答案不满足,收缩右边界
            else l = mid;    //此时满足,扩大左边界
        }
        return l;
    }
};

————————————————————————————————————————————
除了二分法,我们可以用排序的方式,索引值H一开始给0,只要找到比我索引值大的就+1 。
至少满足N个论文索引值是大于等于N的,所以就是看当h=1是否满足满足,当h=2是否满足 满足就给他继续找找找。一开始是0

class Solution {
public:
    int hIndex(vector<int>& citations) {
        sort(citations.begin(), citations.end());
        int h = 0, i = citations.size() - 1;
        while (i >= 0 && citations[i] > h) {
            h++;
            i--;
        }
        return h;
    }
};

或者计数排序

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int n = citations.size(), tot = 0;
        vector<int> counter(n + 1);
        for (int i = 0; i < n; i++) {
            if (citations[i] >= n) {
                counter[n]++;
            } else {
                counter[citations[i]]++;
            }
        }
        for (int i = n; i >= 0; i--) {
            tot += counter[i];
            if (tot >= i) {
                return i;
            }
        }
        return 0;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值