Java Binary Search Solution O(nlogn) + O(1) Space


  • 0
    public class Solution {
        public int hIndex(int[] citations) {
            if (citations == null || citations.length == 0) {
                return 0;
            }
            int start = 0;
            int end = citations.length;
            while (start + 1 < end) {
                int mid = start + (end - start) / 2;
                if (helper(citations, mid) < mid) {
                    end = mid;
                } else {
                    start = mid;
                }
            }
            
            if (helper(citations, end) == end) {
                return end;
            }
            return start;
        }
        
        public int helper(int[] citations, int h) {
            int count = 0;
            for (int c : citations) {
                if (c >= h) {
                    count++;
                }
            }
            return count;
        }
    }
    

Log in to reply
 

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