C# O(nlogn) solution with explanation

  • 0
    public int HIndex(int[] citations) 
            if (citations.Length == 0) return 0;
            if (citations.Length == 1) return citations[0] == 0 ? 0 : 1;
            var result = 0;
           for (int i = 0; i < citations.Length; i++)
                if (citations[i] >= citations.Length - i) 
                   result = citations.Length - i; break;
            return result;

    First we sort the array, and then we check if the number of values from a particular index to the end of the array satisfies the H-index property : 'h of his papers have at least a value of h (or above)'

    Since we are doing it in ascending order, the result value which satisfies the condition will always be largest possible, and we will get the highest possible H-index, so we can exit the loop and return the value.

Log in to reply

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