小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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测试程序源码

posted on 2015-11-30 13:28  Coding菌  阅读(94)  评论(0编辑  收藏  举报