问题连接:https://leetcode.com/problems/h-index/和https://leetcode.com/problems/h-index-ii/
这两个问题属于一个问题,第二个的引用数数组已经排序,有对数时间复杂度要求。H-index的概念理解还是很挠头的。举个例子:
0 3 5 5 6和0 1 3 5 6:到底是数组值(高被引文章的引用数)重要还是高被引篇数重要呢?显然是高被引篇数(科研防止灌水的指标),篇数大于等于某个数组值时才可能是H-index,说明
思路:先排序,然后搜索,最坏时间复杂度为O(n)。
class Solution {
public int hIndex(int[] citations) {
//0 3 5 5 6
Arrays.sort(citations);
int i=0;
for(;i<citations.length;i++)
{
if(citations[i]>=citations.length-i)
break;
}
return citations.length-i;
}
}
思路:要求对数复杂度,既然是对数复杂度,那必然是用二分法,这里使用左闭右闭区间的二分法版本,这种写法要注意每次while循环都要判断等于目标值的情况,对于左右值的变化可以举几个例子帮助自己理解,如下几个例子:
//0 3 5 5 6
//0 1 2 2 5 6
//0 1 5 5 5 6
class Solution {
public int hIndex(int[] citations) {
//0 3 5 5 6
//0 1 2 2 5 6
//0 1 5 5 5 6
int lo=0,hi=citations.length-1;
while(lo<=hi)
{
int mid=lo+(hi-lo)/2;
if(citations[mid]==citations.length-mid)//找到第一个引用数等于篇数,直接返回篇数
return citations.length-mid;
else if(citations[mid]<citations.length-mid)//引用数小于大于等于该引用数文章的篇数,例如0 1 2 2 5 6的2<4,需要向后继续搜索
lo=mid+1;
else
hi=mid-1;//引用数大于大于等于该引用数文章的篇数(说明较高水平文章占了超过一半),例如0 1 5 5 5 6的5>4,需要向前继续搜索
}
return citations.length-lo;
}
}
这个解法Beat 100%真的爽歪歪!!!我们一定要掌握二分搜索的两种bugfree的写法,不能混淆!