原题网址: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;
}
}

本文介绍了一种在已排序引用数组中优化H指数计算的方法,通过使用二分查找将时间复杂度降低到O(log n),并提供了两种不同的二分查找实现方式。
2303

被折叠的 条评论
为什么被折叠?



