美文网首页
274&275. H-Index

274&275. H-Index

作者: exialym | 来源:发表于2016-11-15 16:29 被阅读9次

274

Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
这道题比较容易的办法是直接排序,然后从后往前找,找到n篇引用大于n的就返回n。
但是这样排序至少需要O(nlogn)的时间复杂度。
还有一种办法,使用额外的一个数组记录每种引用数的文章有多少篇,引用数最多记到文章数,因为H-index不可能超过文章数。

var hIndex = function(citations) {
    var stats = [];
    var n = citations.length;
    // 统计各个引用次数对应多少篇文章
    for(let i = 0; i < n; i++){
        let index = citations[i] <= n ? citations[i] : n;
        stats[index] === undefined ? 
        stats[index] = 1:
        stats[index] += 1;
    }
    var sum = 0;
    // 找出最大的H指数
    for(let i = n; i > 0; i--){
        // 引用大于等于i次的文章数量,等于引用大于等于i+1次的文章数量,加上引用等于i次的文章数量 
        sum += stats[i]===undefined ? 0 :stats[i];
        // 如果引用大于等于i次的文章数量,大于引用次数i,说明是H指数
        if(sum >= i){
            return i;
        }
    }
    return 0;
}

275

这个问题在前面问题的基础上,给了一个有序的数组,那就从后往前,或二分查找。

var hIndex = function(citations) {
    // var num = citations.length;
    // var count = 0;
    // for (let i = num - 1;i >= 0;i--) {
    //     count++;
    //     if (citations[i]===count)
    //         return count;
    //     else if (citations[i]<count)
    //         return --count;
    // }
    // return num;
    var l = 0;
    var r = citations.length-1;
    var num = citations.length;
    while (l<=r) {
        var mid = parseInt(l + (r - l) / 2);
        var count = num - mid;
        if (citations[mid]===count)
            return count;
        else if (citations[mid]<count)
            l = mid + 1;
        else
            r = mid - 1;
    }
    return num - r - 1;
};

相关文章

  • 274&275. H-Index

    274 Given an array of citations (each citation is a non-n...

  • 2019-02-05

    LeetCode 275. H-Index II Description Given an array of ci...

  • 275. H-Index II

    Question Follow up for H-Index: What if the citations arr...

  • 275. H-Index II

  • 274. H-Index, 275. H-Index II

    274 就先sort一下,再遍历一遍从高到低排序,然后从左向右扫。如果一个数的值大于等于他的index + 1,则...

  • [Leetcode]275. H-Index II

    一、问题链接:https://leetcode.com/problems/h-index-ii/descripti...

  • Leetcode-275题:H-IndexII

    题目 Follow up for H-Index: What if the citations array is ...

  • 2019-02-05

    LeetCode 274. H-Index Description Given an array of citat...

  • ARTS 第22周

    ARTS 第22周分享 [TOC] Algorithm 274. H-Index [medium] [题目描述] ...

  • H-Index

    题目来源计算作者的H指数,有h篇paper的引用不小于h,那么h指数就是h。我想着排个序,然后从头往后遍历一下就可...

网友评论

      本文标题:274&275. H-Index

      本文链接:https://www.haomeiwen.com/subject/wcflpttx.html