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.
solution:
Binary search.
public int hIndex(int[] citations) {
if(citations.length <=0) return 0;
int len = citations.length;
int start = 0;
int end = len-1;
while(start<=end) {
int mid = start + (end-start)/2;
if(citations[mid] == len-mid) return len-mid;
else if (citations[mid] < len-mid) start = mid+1;
else end = mid-1;
}
return len-start;
}

本文介绍了一种针对已排序引用数组的H-Index算法优化方案,通过二分查找实现O(log n)的时间复杂度,显著提高了算法效率。
480

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



