题目:
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 n = citations.size();
int low = 0, high = n - 1;
int h = 0;
while (high >= low){
int mid = low + (high - low) / 2;
//找到,直接返回
if ((n - mid) == citations[mid]) return n - mid;
//更新h
int hNew = ((n - mid) < citations[mid])?(n-mid):citations[mid];
if (h < hNew) h = hNew;
//二分查找
if ((n - mid) < citations[mid]) high = mid - 1;
else low = mid + 1;
}
return h;
}
};