题目
Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
答案
class Solution {
public int hIndex(int[] citations) {
int left = 0, right = citations.length - 1, max = 0;
while(left <= right) {
int mid = left + (right - left) / 2;
if(citations[mid] >= (citations.length -1 - mid + 1)) {
max = Math.max(max, (citations.length -1 - mid + 1)); // Go Left
right = mid - 1;
}
else
left = mid + 1; // Go right
}
return max;
}
}