AC Java code using Hashtable and Arrays.sort


  • 0
    H

    General idea: sort citations array in descending order, and if f(i) > i, put (i, f(i)) into hashtable. Finally, return hashtable.size() as h-index. Here is my AC Java code using Hashtable. Would you please give me some suggestion or comments ? Thanks.

      // https://en.wikipedia.org/wiki/H-index
    public int hIndex(int[] citations) {
        if (citations == null || citations.length == 0) return 0;
        
        Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();
    
        Arrays.sort(citations);
        
        int[] A = citations;
        int len = A.length;
       
       // sort citation array in descending order
       for(int i = 0; i <len / 2; i++){
            int temp = A[i];
            A[i] = A[len - i - 1];
            A[len - i - 1] = temp;
        }
       
       // add citation > index eg. [6, 5, 3, 1, 0], add <6,0> <5,1> <3,2> into Hashtable
        for (int i=0; i<A.length; i++) {
            if ( A[i] > i) {
                ht.put(i, A[i]);
            }
        }
        return ht.size();
    }

Log in to reply
 

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