Problem
Follow up for H-Index: What if the citations
array is sorted in ascending order? Could you optimize your algorithm?
Solution 二分查找
找满足条件的最左边缘的数,所以向左移动的时候要宽松一点。
class Solution {
public:
int hIndex(vector<int>& arr) {
const int N = arr.size();
int left = 0, right = N -1 ;
for( ; left <= right; ){
int mid = (left + right)/2;
int right_num = N - mid;
if( right_num <= arr[mid] ){
right = mid - 1;
}
else {
left = mid + 1;
}
}
return N - left;
}
};