H-Index

题目链接:https://leetcode.com/problems...

sort:

public class Solution {
    public int hIndex(int[] citations) {
        if(citations == null || citations.length == 0)  return 0;
        // sort
        Arrays.sort(citations);
        int n = citations.length;
        // find 1st i that citations[i] < i
        // [0, 1, 3, 5, 6]
        for(int i = 0; i < n; i++) {
            if(citations[i] >= n - i) return n - i;
        }
        return 0;
    }
}

calculate suffix sum:

public class Solution {
    public int hIndex(int[] citations) {
        if(citations == null || citations.length == 0)  return 0;
        int n = citations.length;
        int[] count = new int[n + 1];
        for(int i = 0; i < n; i++) {
            if(citations[i] > n) {
                count[n]++;
            }
            else {
                count[citations[i]]++;
            }
        }
        
        // calculate suffix sum
        int sum = 0;
        for(int i = n; i >= 0; i--) {
            sum += count[i];
            if(sum >= i) return i;
        }
        return 0;
    }
}

H-Index II

题目链接:https://leetcode.com/problems...

public class Solution {
    public int hIndex(int[] citations) {
        if(citations == null || citations.length == 0)  return 0;
        // binary search, find 1st c[i] >= n - i
        int n = citations.length;
        int l = 0, r = n - 1;
        while(l + 1 < r) {
            int mid = l + (r - l) / 2;
            int val = citations[mid];
            if(val == n - mid) return n - mid;
            else if(val < n - mid) l = mid;
            else r = mid;
        }
        
        if(citations[l] >= n - l) return n - l;
        if(citations[r] >= n - r) return n - r;
        return 0;
    }
}

lulouch13
13 声望6 粉丝