Leetcode 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.
提示是log(n)的话肯定用二分搜索了:
class Solution {
public:
int hIndex(vector<int>& citations) {
int len = citations.size();
int lo = 0;
int hi = len;
while (lo < hi) {
int mid = (lo + hi) / 2;
int remain = len - mid;
if (citations[mid] >= remain) {
hi = mid;
} else {
lo = mid + 1;
}
}
return len - lo;
}
};