LeetCode – H-Index II (Java)

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

Java Solution

Given the array is sorted, we should use binary search.

int hIndex(int[] citations) {
    int len = citations.length;
 
    if (len == 0) {
        return 0;
    }
 
    if (len == 1) {
        if (citations[0] == 0) {
            return 0;
        } else {
            return 1;
        }
    }
 
    int i = 0;
    int j = len - 1;
    while (i < j) {
        int m = i + (j - i + 1) / 2;
        if (citations[m] > len - m) {
            j = m - 1;
        } else {
            i = m;
        }
    }
 
    if (citations[j] > len - j) {
        return len;
    }
 
    if (citations[j] == len - j) {
        return len - j;
    } else {
        return len - j - 1;
    }
}

2 thoughts on “LeetCode – H-Index II (Java)”

  1. More simpler version can be :

    if (citations == null || citations.length == 0) {
    return 0;
    }

    int n = citations.length;
    int i = 0, j = n-1;

    while (i <= j) {
    int m = (i + j) / 2;

    if (citations[m] < n – m) {
    i = m + 1;
    } else {
    j = m – 1;
    }
    }

    return n – i;
    }

  2. Could you simplify using following code.

    public int hIndex(int[] citations) {
    if (citations == null || citations.length == 0) {
    return 0;
    }

    int n = citations.length;
    int i = 0, j = n-1;

    while (i <= j) {
    int m = i + (j - i) / 2;

    if (citations[m] < n - m) {
    i = m + 1;
    } else {
    j = m - 1;
    }
    }

    return n - i;
    }

Leave a Comment