Leetcode 275. H-Index II (Medium) (cpp)
Tag: Binary Search
Difficulty: Medium
/*
275. H-Index II (Medium)
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 _size = citations.size();
int l = 0, r = _size - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (citations[mid] < _size - mid) l = mid + 1;
else if (citations[mid] > _size - mid) r = mid - 1;
else return citations[mid];
}
return _size - l;
}
};