Simple solution in Java with 0(1) space.


  • 1
    M

    I tried this problem for more than one hour. I found different solutions using bucket sort and additional data structures in use. But after many test cases, I came up this solution.

    This is how it works:
    Here h = n - i, where n is the total number of papers.
    Initially, sort the given array in an increasing order.

    1. If we found index 'h' with exactly same value as the number of papers with at least 'h' citations, update the variable "val" with 'h'.
    2. ElseIf, the number of papers is less than the current index, it means that we have 'h' papers with at least 'h' citations each as " citations[i] > h ". But the most important thing is we need to be careful of previous "val". To better understand, please try with different possible test cases.
    public class Solution {
        public int hIndex(int[] citations) {
            if( citations.length == 0 )
                return 0;
            int val = 0, n = citations.length;
            Arrays.sort(citations);
            for( int i = 0; i < n; i++ )
            {
                if( citations[i] == (n - i) )
                    val = citations[i];
                else if( citations[i] > (n - i) )
                {
                    if( val < (n - i) )
                        val = n - i;
                }
            }
            return val;
        }
    }
    

Log in to reply
 

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