O(n) Quick Select solution in C#.


  • 0
    L
    private int QuickSelect(int[] nums, int start, int end){
            if (start == end){
                if (nums[start] >= nums.Length - start)
                    return nums.Length - start;
                else
                    return 0;
            }
                
            
            int sd = nums[start];
            int left = start;
            int right = end;
            
            while (left < right){
                while (left < right && sd <= nums[right])
                    right--;
                nums[left] = nums[right];
                
                while (left < right && nums[left] <= sd)
                    left++;
                nums[right] = nums[left];
            }
            
            nums[left] = sd;
            int k = nums.Length - left; // nums[left] is the Kth largest number in citations. 
            
            if (nums[left] < k)  // k is too large, thus we need a larger number
                return QuickSelect(nums, left + 1, end);
            else
                return QuickSelect(nums, start, left);
        }
        
        public int HIndex(int[] citations) {
            if (citations == null || citations.Length == 0)
                return 0;
            
            return QuickSelect(citations, 0, citations.Length - 1);
        }
    

Log in to reply
 

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