• 274. H-Index


    题目:

    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."

    For example, given citations = [3, 0, 6, 1, 5], which 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, his h-index is 3.

    Note: If there are several possible values for h, the maximum one is taken as the h-index.

    Hint:

    1. An easy approach is to sort the array first.
    2. What are the possible values of h-index?
    3. A faster approach is to use extra space.

    链接: http://leetcode.com/problems/h-index/

    题解:

    求H-Index,找在数组中有k个元素大于等于k。排序一下再进行计算就比较容易些了。 也可以用index-couting,但这样就需要一个额外的数组。

    Time Complexity - O(nlogn), Space Complexity - O(1)。

    public class Solution {
        public int hIndex(int[] citations) {
            if(citations == null || citations.length == 0) {
                return 0;
            }
            int len = citations.length;
            for(int i = 0; i < len; i++) {
                if(citations[i] >= len - i) {    // check if we have len - i elements larger than len - i
                    return len - i;
                }
            }
            return 0;
        }
    }

    Index counting:

    Time Complexity - O(n), Space Complexity - O(n)

    public class Solution {
        public int hIndex(int[] citations) {
            if(citations == null || citations.length == 0) {
                return 0;
            }
            int len = citations.length;
            int[] count = new int[len + 1];
            for(int num : citations) {
                if(num > len) {
                    count[len]++;
                } else {
                    count[num]++;
                }
            }
            
            int sum = 0;
            for(int i = len; i >= 0; i--) {
                sum += count[i];
                if(sum >= i) {
                    return i;
                }
            }
            
            return 0;
        }
    }

    Reference:

    https://leetcode.com/discuss/55958/my-easy-solution

    https://leetcode.com/discuss/56041/a-clean-o-n-solution-in-java

    https://leetcode.com/discuss/55952/my-o-n-time-solution-use-java

    https://leetcode.com/discuss/55950/1-line-ruby-5-lines-c-6-lines-java

    https://leetcode.com/discuss/66656/java-o-n-time-with-easy-explanation

  • 相关阅读:
    假期第九天
    假期第八天
    8.9周总结
    构建之法阅读笔记之三
    构建之法阅读笔记之二
    构建之法阅读笔记之一
    03人月神话阅读笔记之一
    手机输入法使用评价
    十天冲刺-第十天
    十天冲刺-第九天
  • 原文地址:https://www.cnblogs.com/yrbbest/p/5031910.html
Copyright © 2020-2023  润新知