Share my 12-line java code with a binary search trick (left < right-1)


  • 0
    M
    public class Solution {
        public int hIndex(int[] citations) {
            if (citations==null || citations.length==0) { return 0; }
            int len = citations.length;
            int left = 0, right = len-1;
            while (left < right-1) {
                int mid = left + (right-left)/2;
                if (citations[mid] >= len-mid) { right = mid; }  // we want to find the first one, go left
                else { left = mid; }
            }
            if (citations[left] >= len-left) { return len-left; }
            else if (citations[right] >= len-right) { return len-right; }
            return 0;
        }
    }

Log in to reply
 

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