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

weixin_34391854發表於2015-09-05

 

Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?

Hint:

  1. Expected runtime complexity is in O(log n) and the input is sorted.

 

這題是之前那道H-Index 求H指數的擴充,輸入陣列是有序的,讓我們在O(log n)的時間內完成計算,看到這個時間複雜度,應該有很敏銳的意識應該用二分查詢法,我們最先初始化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;
    }
};

 

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

 

相關文章