H-Index II
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.
class Solution {
public:
int hIndex(vector<int>& citations) {
if(citations.empty()) return 0;
int l = 0, r = citations.size()-1;
while(l <= r){
int m = l+((r-l)>>1);
//这个判断语句表示citations[m]位于数组下标为citations.size()-m处,也就是说
//大于等于citations[m]的数的个数为m个
if(citations.size()-m == citations[m]) return citations[m];
else if(citations.size()-m > citations[m]) l = m+1;
else if(citations.size()-m < citations[m]) r = m-1;
}
return citations.size()-l;
}
};