您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]H-Index II

2015-09-05 01:28 615 查看

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.

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

紧接着上一题:/article/7171017.html

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


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

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


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

len - indexindexcitations[index]
500
411
323
235
146
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。

* @param {number[]} citations
* @return {number}
*/
var hIndex = function(citations) {
var len = citations.length;
var start = 0, end = len, index;
while(start <= end){
index = parseInt((start + end) / 2);
if(citations[index] === undefined){
return 0;
}
if(citations[index] >= len - index){
end = index - 1;
}else{
if(citations[index + 1] >= len - index - 1){
return len - index - 1;
}else{
start = index + 1;
}
}
}
return len;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: