The idea is to search for the first index from the sorted array so that :
citations[index] >= length(citations) - index.
And return (length - index) as the result.
99.93 %
class Solution {
public int hIndex(int[] citations) {
if (citations == null || citations.length == 0) {
return 0;
}
// [1, 2, 3, 3]
int start = 0;
int end = citations.length - 1;
int len = citations.length;
while (start < end) {
int mid = start + (end - start) / 2;
// [mid, end] -> all have at least citations[mid] citations each
if (citations[mid] >= len - mid) {
end = mid;
} else if (citations[mid] < len - mid + 1) {
start = mid + 1;
}
}
return citations[start] >= len - start ? len - start : 0;
}
}
No comments:
Post a Comment