C++ Solution using binary search with O(logn) Time & O(1) Space


  • 0
    Y
    class Solution {
    public:
        int hIndex(vector<int>& citations) {
            int ans = 0;
            if(!citations.size())
                return ans;
            int l = 0, r = citations.size() - 1, n = citations.size();
            while(l <= r){
                int mid = (l + r)>>1;
                ans = max(ans, min(citations[mid], n - mid));
                if(citations[mid] <= n - mid){
                    l = mid + 1;
                }else{
                    r = mid - 1;
                }
            }
            return ans;
        }
    };

Log in to reply
 

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