Share my C++ solution using 'Binary Search',easy to understand


  • 0
    V
    class Solution {
    public:
        int hIndex(vector<int>& citations) {
            int n = citations.size();
            
            if (n == 0)
                return 0;
                
            int i = 0;
            int left = 0, right = n-1, mid = 0;
            
            while (left <= right)
            {
                mid = left + (right - left) / 2;
                
                if (citations[mid] == (n-mid))
                    return n-mid;
                else if (citations[mid] > (n-mid))
                    right = mid-1;
                else
                    left = mid+1;
            }
            
            return n-left;
        }
    };

Log in to reply
 

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