原题网址:https://leetcode.com/problems/h-index-ii/
Follow up for H-Index: What if the citations
array is sorted in ascending order? Could you optimize your algorithm?
Hint:
- Expected runtime complexity is in O(log n) and the input is sorted.
方法一:从大到小扫描,时间复杂度O(n)
public class Solution {
public int hIndex(int[] citations) {
int h=0;
for(int i=citations.length-1; i>=0 && citations[i]>h; i--,h++);
return h;
}
}
方法二:二分法查找,时间复杂度O(logn)
public class Solution {
public int hIndex(int[] citations) {
int i=0, j=citations.length-1;
while (i<=j) {
int m = (i+j) >> 1;
if (citations[m] == citations.length-m) return citations.length-m;
if (citations[m] > citations.length-m) j=m-1; else i=m+1;
}
return citations.length-i;
}
}
另一种实现:
public class Solution {
public int hIndex(int[] citations) {
int i=0, j=citations.length-1;
while (i<=j) {
int m=(i+j)/2;
if (citations[m]>=citations.length-m) j=m-1; else i=m+1;
}
return citations.length-i;
}
}