[LeetCode] H-Index II 求H指數之二


 

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 的拓展,輸入數組是有序的,讓我們在 O(log n) 的時間內完成計算,看到這個時間復雜度,而且數組又是有序的,應該有很敏銳的意識應該用二分查找法,屬於博主之前的總結帖 LeetCode Binary Search Summary 二分搜索法小結 中的第五類,目標值 target 會隨着 mid 值的變化而變化,這里的 right 的初始值和 while 循環條件是否加等號是需要注意的問題,一般來說,博主的習慣是把 right 初始化為數組的長度,然后循環條件中不加等號,但是這種 right 的初始化對於這種目標值不固定的情況下不好使,需要初始化為長度減1(目前博主還沒有遇到反例,有的話請務必告知博主)。那么此時循環條件中是否要加等號,這個其實很玄學,在 Find Peak Element 中,right 也是初始化為數組長度減1,但是循環條件卻不能加等號。這道題卻一定需要加等號,否則會跪在 [0] 這個 test case,有些時候固有的規律並不好使,可能只能代一些 corner case 來進行檢驗,比如 [], [0], [1,2] 這種最簡便的例子。

基於上面的分析,我們最先初始化 left 和 right 為0和 len-1,然后取中間值 mid,比較 citations[mid] 和 len-mid 做比較,如果前者大,則 right 移到 mid 之前,反之 right 移到 mid 之后,循環條件是 left<=right,最后返回 len-left 即可,參見代碼如下:

 

class Solution {
public:
    int hIndex(vector<int>& citations) {
        int len = citations.size(), left = 0, right = len - 1;
        while (left <= right) {
            int mid = 0.5 * (left + right);
            if (citations[mid] == len - mid) return len - mid;
            else if (citations[mid] > len - mid) right = mid - 1;
            else left = mid + 1;
        }
        return len - left;
    }
};

 

類似題目:

H-Index

 

參考資料:

https://leetcode.com/problems/h-index-ii/

https://leetcode.com/problems/h-index-ii/discuss/71063/Standard-binary-search

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM