问题描述:
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 h citations each."
Example:
Input:citations = [0,1,3,5,6]Output: 3 Explanation:[0,1,3,5,6]means the researcher has5papers in total and each of them had received 0, 1, 3, 5, 6citations respectively. Since the researcher has3papers with at least3citations each and the remaining two with no more than3citations each, her h-index is3.
Note:
If there are several possible values for h, the maximum one is taken as the h-index.
Follow up:
citations is now guaranteed to be sorted in ascending order.
解题思路:
这道题目是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; } };
原文:https://www.cnblogs.com/yaoyudadudu/p/9315828.html