H-Index II
描述
Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
分析
设数组长度为n
,那么n-i
就是引用次数大于等于nums[i]
的文章数。如果nums[i]<n-i
,说明i
是有效的H-Index, 如果一个数是H-Index,那么最大的H-Index一定在它后面(因为是升序的),根据这点就可以进行二分搜索了。
代码
// H-Index II
// Time complexity: O(logn), Space complexity: O(1)
public class Solution {
public int hIndex(int[] citations) {
final int n = citations.length;
int begin = 0;
int end = citations.length;
while (begin < end) {
final int mid = begin + (end - begin) / 2;
if (citations[mid] < n - mid) {
begin = mid + 1;
} else {
end = mid;
}
}
return n - begin;
}
}