275. H-Index II

Posted yaoyudadudu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了275. H-Index II相关的知识,希望对你有一定的参考价值。

问题描述:

Given an array of citations sorted in ascending order (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 citations each."

Example:

Input: citations = [0,1,3,5,6]
Output: 3 
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had 
             received 0, 1, 3, 5, 6 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.

Note:

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

Follow up:

  • This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
  • Could you solve it in logarithmic time complexity?

 

解题思路:

这道题目是h-index的一个follow up,是说给定数组已经排好序了怎么做。

有要求时间复杂度在logn上。

显然想到二分搜索。

先来找一下上界和下届:从题目描述来看: 0 ≤ h ≤ N, 所以l = 0, r = n

然后来找移动的条件:

h-index的定义是:h篇论文的引用要至少为h,余下的(N-h)篇论文的引用都不能超过h

说明是引用数值和论文个数的关系。

求个数:n - i; n : citations.size() , i : 下标

求引用数:citations[i]

所以当n - i == citations[i]时: 代表:有citations篇论文的引用至少为citations[i], 余下的最多为citations[i],可以直接返回

若citations[i] < n-i 时:引用数小于论文篇数,所以我们应该增大引用数并减小论文数:left = i+1

若citations[i] > n-i 时:引用数大于论文篇数,所以我们应该增大论文数并减小引用数:right = i

 

最后n-left为h-index

 

代码:

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int n = citations.size();
        if(n == 0 || citations[n-1] == 0)
            return 0;
        int l = 0, r = n;
        while(l < r){
            int mid = l + (r - l)/2;
            if(citations[mid] == n - mid) return n - mid;
            else if(citations[mid] < n - mid) l = mid + 1;
            else r = mid;
        }
        return n - l;
    }
};

 

以上是关于275. H-Index II的主要内容,如果未能解决你的问题,请参考以下文章

java 275. H-Index II(#)。java

java 275. H-Index II(#)。java

java 275. H-Index II(#)。java

java 275. H-Index II(#)。java

java 275. H-Index II(#)。java

275. H-Index II