[LeetCode] 274. H-Index

H-Index是一个判断发表论文质量的参数。这个参数的定义是,如果作者发布了N篇论文,其中有h篇论文至少被引用了h次;剩下的论文的被引用次数都不超过h次。

Input: citations = [3,0,6,1,5]
Output: 3 
Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had 
             received 3, 0, 6, 1, 5 citations respectively. 
             Since the researcher has 3 papers with at least 3 citations each and the remaining 
             two with no more than 3 citations each, her h-index is 3.

两种思路,第一种是排序;第二种是用到桶排序。

排序法:例子,

[3,0,6,1,5]

按照从大到小排序,排序过后的数组为[6, 5, 3, 1, 0]。此时扫描数组,判断下标i是否 >= citation[i]。因为一共有n篇论文,所以判断的是是不是至少有i篇论文,被引用的次数大于等于i次。

时间O(nlogn)

空间O(1)

 1 /**
 2  * @param {number[]} citations
 3  * @return {number}
 4  */
 5 var hIndex = function(citations) {
 6     citations = citations.sort((a, b) => b - a);
 7     let len = citations.length;
 8     for (let i = 0; i < len; i++) {
 9         if (i >= citations[i]) {
10             return i;
11         }
12     }
13     return len;
14 };

桶排序

建立一个[citations.length + 1]长度的数组buckets。把被引用次数放在数组该去的位置。按照上面的例子,数组本身的长度为5,如果遇到被引用次数大于5的,也一律放在下标为5的位置上。从右往左再次遍历这个buckets,如果遍历到某一个引用次数时,大于或等于该引用次数的文章数量,大于引用次数本身时,我们可以认为这是H指数。

时间O(n)

空间O(n)

 1 /**
 2  * @param {number[]} citations
 3  * @return {number}
 4  */
 5 var hIndex = function(citations) {
 6     const buckets = Array(citations.length + 1).fill(0);
 7     citations.forEach(citation => {
 8         buckets[citation >= citations.length ? citations.length : citation]++;
 9     });
10     let count = 0;
11     for (let i = citations.length; i >= 0; i--) {
12         count += buckets[i];
13         if (count >= i) {
14             return i;
15         }
16     }
17     return 0;
18 };

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/11756535.html