Java O(n) concise solution


  • 1
    J
    public class Solution {
        public int hIndex(int[] citations) {
            int res, len;
            res = len = citations.length;
            int[] count = new int[len + 1];
            for(int i : citations){
                if(i < res){
                    if(count[res] == 0){
                        res--;
                    }
                    else{    
                        count[res]--;
                    }
                    count[i]++;
                }
            }
            return res;
        }
    }
    

    First set h-index to array.length, if we encounter a number less than current h, h should subtract by one. But, if we previously used higher standards and ruled out a number that shouldn't have been under current h, we don't do h--.


  • 0
    S

    Hi, for this line

    int[] count = new int[len + 1];
    

    I think you may not use len + 1, but max(citations). Otherwise you should see run time error when you do

    count[i]++;
    

    if i > len + 1.


  • 0
    J
    This post is deleted!

  • 0
    J

    @seeker_13 but count[i]++was placed in an ifsentence, so index shouldn't exceed the limit.


  • 0
    S

    @jiaao Oh yeah, that's right. We don't need to care about citations greater than N. Thanks for your sharing!


Log in to reply
 

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