Description:
Follow up for H-Index: What if the citations
array is sorted in ascending order? Could you optimize your algorithm?
Solution:
The problem is very similar to former one. For last problem, we have notice that there exists a formula: if we order the number in an descending order, then the last index that satisfies the arr[i] >= i+1 is the answer.
And this is very similar in this problem, the only difference is that given the ascending array.
Notice that we can pre-operate the array, and citations[n-1-i] -= i+1, which will maintain the ascending order.
And due to the ascending order, we can use binary-search to find the largest index with citations[index] < 0, so the length or h is n-1-index.
<span style="font-size:18px;">public class Solution {
public int hIndex(int[] citations) {
int n = citations.length;
for (int i = 0; i < n; i++)
citations[n - 1 - i] -= i + 1;
if (n == 0)
return 0;
if (citations[n - 1] < 0)
return 0;
if (citations[0] >= 0)
return n;
int l = 0, r = n - 1, mid;
while (l + 1 < r) {
mid = (l + r) / 2;
if (citations[mid] >= 0)
r = mid;
else
l = mid;
}
return n - l - 1;
}
}
</span>