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.
排序了,可以用二分查找了。
二分查找的时候由于不是找某个特定的元素,而是找一个【尽量靠左】的index使得citations[index]>=len-index,所以进入左子区间前先检查一下,以免漏掉要查找的位置。
例如[1,2,5,6,8],第一次搜索mid=2,如果进入左区间,左区间里没有index满足条件,将错过要查找的位置。
又例如[1,4,5,6,8],第一次搜索mid=2,应该进入左区间,因为index=1,满足条件。
为了区分以上两种情况,进入左区间前做检查,看看当mid-1>=lo时是否满足
citations[mid-1]>=len-mid+1
满足就可以继续进入左区间查找。
public int hIndex(int[] citations)
{
int len=citations.length;
if(len<1)
return 0;
int index=find(citations, 0, len-1);
if(citations[index]<len-index)
return 0;
return len-index;
}
public int find(int[] citations,int lo,int hi)
{
if(lo==hi)
return lo;
int mid=(lo+hi)>>1;
if(citations[mid]>=citations.length-mid)
{
if(mid-1>=lo&&(citations[mid-1]>=citations.length-mid+1))
return find(citations, lo, mid-1);
return mid;
}
return find(citations, mid+1,hi);
}