Python Binary Search


  • 0
    class Solution(object):
        def hIndex(self, citations):
            if not citations:
                return 0
            left, right = -1, len(citations) - 1
            while right - left > 1:
                mid = (left + right) >> 1
                if citations[mid] >= len(citations) - mid:
                    right = mid
                else:
                    left = mid
            return min(len(citations) - right, citations[right])
    

  • 0

    Find first index i in sorted array { citations[i]-(n-i) } such that citations[i]-(n-i) >= 0:

        int hIndex(vector<int>& c) {
            int L = -1, R = c.size(), mid;// index range [0,n] = (-1,n] for int
            while(R - L > 1) if(c[mid = L + (R - L)/2] >= c.size() - mid) R = mid; else L = mid;
            return c.size() - R;
        }
    

Log in to reply
 

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