[LeetCode][JavaScript]H-Index II
2015-09-05 01:28
615 查看
H-Index II
Follow up for H-Index: What if thecitationsarray 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 - index | index | citations[index] |
5 | 0 | 0 |
4 | 1 | 1 |
3 | 2 | 3 |
2 | 3 | 5 |
1 | 4 | 6 |
如果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; };
相关文章推荐
- 创建自己的库 ADS.js(第一版本)
- [LeetCode][JavaScript]H-Index
- 自己的JS调试工具 myLogger()对象
- emberjs体验
- Go学习笔记:json处理
- JSP执行过程
- JS基础
- JavaScript中常用的函数以及基础写法汇总
- 解决jsp页面汉字乱码问题
- Javascript高级程序设计——this、闭包、函数表达式
- JavaScript基础知识
- javascript中的each遍历
- 两个简单实用的js代码
- JavaScript-函数,类,数组
- json解析中的坑+解析方法
- 最简明的JavaScript闭包解释
- jsp内置九大对象
- 用js实现透明度渐变效果
- JavaScript之浏览器对象编程练习
- javascript学习笔记(四):事件处理函数和动态创建html标记。