[LeetCode][JavaScript]H-Index II

H-Index II

Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?

Hint:

  1. Expected runtime complexity is in O(log n) and the input is sorted.

https://leetcode.com/problems/h-index-ii/

 

 


 

 

紧接着上一题:http://www.cnblogs.com/Liok3187/p/4782658.html

给定的数组是升序的,要求时间复杂度为O(logn),二分法。

h代表“高引用次数”(high citations),一名科研人员的h指数是指他至多有h篇论文分别被引用了至少h次。

要确定一个人的h指数非常容易,到SCI网站,查出某个人发表的所有SCI论文,让其按被引次数从高到低排列,往下核对,直到某篇论文的序号大于该论文被引次数,那个序号减去1就是h指数。

还是找拐点,拿上一题的数据举例:[0, 1, 3, 5, 6]

len - index index citations[index]
5 0 0
4 1 1
3 2 3
2 3 5
1 4 6

index是数组的下标,用数组的长度len减去index得到的就是我们需要的序号,要拿这个序号和对应下标的值作比较。

如果citations[index] >= len - index,说明结果在数组的前半部分。

否则citations[index] < len - index,两种情况。

1.后一篇论文,citations[index + 1] >= len - ( index + 1 ),说明找到了拐点,输出结果。

2.结果在数组的后半部分。

 

最后还要考虑一种特殊情况,比如[5,6,7]。

做完二分之后找不到结果,因为每篇论文引用的次数都超过了序号,直接输出len就可以了,”h篇论文分别被引用了至少h次“,超过h次还是h。

 

 2  * @param {number[]} citations
 3  * @return {number}
 4  */
 5 var hIndex = function(citations) {
 6     var len = citations.length;
 7     var start = 0, end = len, index;
 8     while(start <= end){
 9         index = parseInt((start + end) / 2);
10         if(citations[index] === undefined){
11             return 0;
12         }
13         if(citations[index] >= len - index){
14             end = index - 1;
15         }else{
16             if(citations[index + 1] >= len - index - 1){
17                 return len - index - 1;
18             }else{
19                 start = index + 1;
20             }
21         }
22     }
23     return len;
24 };

 

 

 

posted @ 2015-09-05 01:28  `Liok  阅读(405)  评论(0编辑  收藏  举报