274. H-Index

274. H-Index

  • 方法1: 暴力解
  • 方法2: counting sort
    • 易错点

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

Example:

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.

方法1: 暴力解

思路:

有至少h篇论文的citation大于等于h。来自wiki的算法

class Solution {
public:
    int hIndex(vector<int>& citations) {
        sort(citations.begin(), citations.end(), greater<int>());
        int n = citations.size();
        for (int i = 0;  i < n; i++){
            if (i >= citations[i]){
                return i;
            }
        }
        return citations.size();
    }
};

方法2: counting sort

思路:

根据定义首先确定h-index最高不可能超过n,最小只能是0。所以可以用一个长度为 n + 1的vector来count,所有citation大于n的都加入count[n]。那么我们要找的就是最大的h s.t. accumulated citation for count[h…n] >= h。从后向前遍历,每次带走一个accumulative的count,第一个满足的就是h-index。

易错点

vector.size() = n + 1

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int n = citations.size();
        vector<int> count(n + 1, 0);
        for (auto c: citations){
            if (c > n) {
                ++count[n];
            }
            else{
                ++count[c];
            }
        }
        for (int i = n; i >= 0; i--){
            if (count[i] >= i)
                return i;
            count[i - 1] += count[i];
        }
        
        return 0;
    }
};

你可能感兴趣的:(array,leetcode)