274. H-Index

T: O(nlogn)
S: O(1)
class Solution {
    public int hIndex(int[] citations) {
        int n = citations.length;
        int left = 0;
        int right = n;

        while (left <= right) {
            int mid = left + (right - left)/2;
            if (citeCount(citations, mid)) {
                if (mid + 1 <= n && !citeCount(citations, mid+1)) {
                    return mid;
                }
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return n; // if citations len is 0 or 1
    }
    private boolean citeCount(int[] citations, int value) {
        int count = 0;
        for (int citation : citations) {
            if (citation >= value) {
                count++;
            }
        }
        return count >= value;
    }
}

/**
T: O(nlogn)
S: O(1)
 */

Last updated

Was this helpful?