Sharing my solution in Java


  • -1
    J
    public class Solution {
        public int hIndex(int[] citations) {
            if(citations == null || citations.length == 0) {
                return 0;
            }
            Arrays.sort(citations);
            int[] arr = new int[citations.length];
            for(int i = 0; i < arr.length; i++) {
                arr[i] = arr.length - i;
            }
            int res = 0;
            for(int i = 0; i < arr.length; i++) {
                if(Math.min(citations[i], arr[i]) > res) {
                    res = Math.min(citations[i], arr[i]);
                }
            }
            return res;
        }
    }

  • 0
    S

    Arrays.sort() is O(nlogn) ;

    public int hIndex(int[] nums) {
        if(nums.length==0) return 0;
        Arrays.sort(nums);
        int count=0,i=nums.length-1;
        while(i>=0&&count<nums[i]){
            count++;
            i--;
        }
        return count;
    }

  • 0
    J

    Thanks for reminding. Yes, Arrays.sort() is O(nlogn)


  • 0
    S

    O(N) solution
    public int hIndex(int[] citations) {
    int n = citations.length;
    int[] hindex = new int[n + 1];
    for(int val: citations){
    if(val >= n) hindex[n]++;
    else hindex[val]++;
    }
    int sum = 0;
    for(int i = n; i > 0; i--){
    sum += hindex[i];
    if(i <= sum){
    sum = Math.max(i, sum - hindex[i]);
    break;
    }
    }
    return sum;
    }


Log in to reply
 

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