H-Index II

275. H-Index II

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

public class Solution {
    public int hIndex(int[] citations) {
        if (citations == null || citations.length == 0) {
            return 0;
        }
        
        int low = 0, high = citations.length - 1;
        int len = citations.length;
        
        while (low <= high) {
            int middle = low + (high - low) / 2;
            
            if (citations[middle] == len - middle) {
                return len - middle;
            } else if (citations[middle] > len - middle) {
                high = middle - 1;
            } else {
                low = middle + 1;
            }
        }
        
        return len - low;
    }
}

Hope this helps,
Michael

DigitalOcean Referral Badge