题目:
Follow up for H-Index: What if the citations
array is sorted in ascending order? Could you optimize your algorithm?
Hint:
- Expected runtime complexity is in O(log n) and the input is sorted.
解题思路:
很明显,此题要考虑使用二分查找。但对于具体做的方法还是不太明白,希望以后能弄懂。
c++版本:
class Solution {
public:
int hIndex(vector<int>& citations) {
int n=citations.size(),lo=0,hi=n-1;
while(lo<=hi)
{
int mid = (lo+hi)>>1;
if(citations[mid]==n-mid)return n-mid;
else if(citations[mid]>n-mid)hi=mid-1;
else
lo=mid+1;
}
return n-lo;
}
};