275. H-Index II

Description

Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?

Solution

Binary search, time O(log n), space O(1)

class Solution {
    public int hIndex(int[] citations) {
        int n = citations.length;
        int left = 0;
        int right = n - 1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            
            if (citations[mid] < n - mid) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        
        return n - left;
    }
}

你可能感兴趣的:(275. H-Index II)