Leetcode: 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(logN) 空间 O(1)

思路

在升序的引用数数组中,假设数组长为N,下标为i,则N - i就是引用次数大于等于下标为i的文献所对应的引用次数的文章数。如果该位置的引用数小于文章数,则说明则是有效的H指数,如果一个数是H指数,那最大的H指数一定在它的后面(因为是升序的)。根据这点就可已进行二分搜索了。这里min = mid + 1的条件是citations[mid] < n - mid,确保退出循环时min肯定是指向一个有效的H指数。

只有一个H指数,就是相等时候书本数目,所以等于就直接return.

本题不同于H-Index I在于,那道题是以citation数来标志H index。因为在那道题中,citation数是连续的,我们这道题,书本数是连续的,所以要以相遇时候右边书本数来标志H-index

By definition, if h of his/her N papers have at least h citations each, then h is the H-index
所以这道题我们就是找citation[k] >= # of books的左边沿,sorted array左边都是citation[k]<#of books, 右边都是citation[k]>=#of books, 左指针和右指针相遇以后左指针l处就是左边沿,len-l就是所求H-index

以[0,1,2,5,6] ,相遇时, l 在5,len-l就是H-index

 

总结:这两道题,看H-index定义很重要,第一题,citation[k]连续,应以citation数目标示H-index, H-index找寻方法应该是:index k is his h-index if the summation of all elements fromcounts[k] to counts[L] is no less than k.  

第二题,#of books连续,应以# of books标示H-index,找寻方法应该是: find h of books that have at least h citations each

 1 public class Solution {
 2     public int hIndex(int[] citations) {
 3         if (citations==null || citations.length==0) return 0;
 4         int len = citations.length;
 5         int l=0, r=len-1;
 6         while (l <= r) {
 7             int m = (l+r)/2;
 8             if (citations[m] == len-m) return len-m;
 9             else if (citations[m] < len-m) {
10                 l = m+1;
11             }
12             else r = m-1;
13         }
14         return len-l;
15     }
16 }

也可以 return len-r-1, 也是对的。因为相遇的时候r刚好在实际指示H-index的数组元素的左侧

转载于:https://www.cnblogs.com/EdwardLiu/p/5074806.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值