O(log n)_C++_Binary search


  • 1
    • I spent lots of time on understanding what H is. In fact just image the vector like a bar and the value of each citations[i] is the height of each factor.

    • Definition: "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."

    • Now you use the H from 0 to n (included) to test all of the factors in the vector. You should find one number of H which makes that that some certain citations[k], the n - k == citations[k], where the k is the value of our expected H.

    • So binary search is applied for Time O(lg n).

    class Solution {
    public:
    int hIndex(vector<int>& citations) {
        if(citations.empty()) return 0;
        int n = citations.size();
        int a = 0, b = n;// because the index range is [0,n].
        while(a < b){
            int i = a + (b - a)/2;
            if(citations[i] > n - i){
                b = i;
            }
            else if(citations[i] < n - i){
                a = i + 1;
            }
            else if(citations[i] == n - i){
                return n - i;
            }
        }
        return n - a;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.