JAVA 2 solutions: (1) with extra space, (2) sort first


  • 0
    S
    //use extra space
    public int hIndex(int[] citations) {
        //TODO
        int n = citations.length;
        int[] map = new int[n + 1];
        for (int val : citations) {
            if (val > n) {
                map[n]++;
            } else {
                map[val]++;
            }
        }
        int counter = 0;
        for (int i = n; i >= 0; i--) {
            counter += map[i];
            if (counter >= i) {
                return i;
            }
        }
        return 0;
    }
    
    
    //sort first
    public int hIndex(int[] citations) {
        Arrays.sort(citations);
        int n = citations.length;
        int h = 0;
        for (int i = 0; i < n; i++) {
            h = Math.max(h, Math.min(n - i, citations[i]));
        }
        return h;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.