Follow up for H-Index: What if the citations
array is sorted in ascending order? Could you optimize your algorithm?
二分查找,时间复杂度O(logn)。
class Solution {
public:
int hIndex(vector<int>& citations) {
int size = citations.size();
int up = size;
int low = 0;
int mid;
while (low < up) {
mid = (up + low) / 2;
if (citations[mid] >= size - mid && (mid <= 0 || citations[mid-1] <= size - mid)) {
return size - mid;
}
else if (citations[mid] >= size - mid) {
up = mid;
}
else {
low = mid + 1;
}
}
return 0;
}
};