题目
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;
}
};