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;
    }
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Praveen

    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;
    }

  • xpress razor

    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;
    }