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
Example:
Input:citations = [0,1,3,5,6]
Output: 3 Explanation:[0,1,3,5,6]
means the researcher has5
papers in total and each of them had received 0, 1, 3, 5, 6
citations respectively. Since the researcher has3
papers with at least3
citations each and the remaining two with no more than3
citations 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:
- 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