问题描述:
Follow up for H-Index: What if the citations
array is sorted in ascending order? Could you optimize your algorithm?
问题分析:
citations数组升序排列,这时候我么可以考虑使用BS搜索算法,找到一个最大的H-index。
过程详见代码:
class Solution {
public:
int hIndex(vector<int>& citations) {
int res = 0;
int n = citations.size();
if (!n) return 0;
int l = 0, r = n - 1;
while (l < r)
{
int mid = l + (r - l) / 2;
if (citations[mid] >= n - mid)
{
r = mid;
}
else
{
l = mid + 1;
}
}
if (citations[l] >= n - l) res = n-l;
return res;
}
};