LeetCode(275)H-Index II

题目

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

分析

LeetCode(274)H-Index第二个版本,给定引用数量序列为递增的;这就省略了我们的第一个排序步骤;

O(n)的时间复杂度,遍历一次即可。

AC代码

class Solution {
public:
    int hIndex(vector<int>& citations) {
        if (citations.empty())
            return 0;

        int len = citations.size(), maxH = 0;
        for (int i = len - 1; i >= 0; --i)
        {
            int h = len - i;
            if (citations[i] >= h && h > maxH)
            {
                maxH = h;
            }
            else{
                break;
            }
        }//for
        return maxH;
    }
};

GitHub测试程序源码

原文地址:https://www.cnblogs.com/shine-yr/p/5214738.html