C# quick sort and take the kth largest


  • 0
    Y
    public class Solution {
      public int FindKthLargest(int[] nums, int k) {
        
        if(k > nums.Length)
        {
            return -1;
        }
        
        //quick sort
        return quickSortK(nums, 0, nums.Length-1,k);
    }  
    
    //quick sort improvement with k
    public int quickSortK(int[] nums, int start, int end,int k)
     {
        var povit = nums[end];
        
    	if(start >= end)
    	{
    		return povit;
    	}
        
        int i=start, j=start;
        int temp=0;
        
        for(; j<end; j++)
        {
            if(nums[j] > povit)
            {
                temp=nums[i];
                nums[i] = nums[j];
                nums[j]=temp;
                i += 1;
            }
        }
        
        nums[end] = nums[i];
        nums[i] = povit;
        
        if(i == k-1)
        {
            return povit;
        }
        else if(i > k-1)
        {
           return quickSortK(nums, start, i-1,k);
        }
        else
        {
           return quickSortK(nums, i + 1, end,k);
         }
     }
     
    }

Log in to reply
 

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