H-Index II
Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
Solution
public class Solution {
public int hIndex(int[] citations) {
if (citations == null || citations.length == 0) return 0;
int size = citations.length;
int start = 0;
int end = size - 1;
while (start <= end) {
int middle = start + (end - start) / 2;
if (size - middle > citations[middle]) {
start = middle + 1;
} else if (size - middle == citations[middle]) {
return citations[middle];
} else {
end = middle - 1;
}
}
return size - start;
}
}