Advertisement
rishu110067

Untitled

Jan 30th, 2022
1,028
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. class Solution {
  2.    
  3.     public static int result = 0;
  4.    
  5.     public int findKthLargest(int[] nums, int k) {
  6.         quickSelect(nums, 0, nums.length-1, k);
  7.         return result;
  8.     }
  9.    
  10.     public void quickSelect(int[] nums, int start, int end, int k) {
  11.         //base
  12.      
  13.         if(start>end) return;
  14.         if(start == end) {
  15.             result = nums[start];
  16.             return;
  17.         }
  18.        
  19.         //recursive case
  20.        
  21.         Random random = new Random();
  22.                
  23.         int pivotIndex = start + random.nextInt(end - start);
  24.        
  25.         //swap pivot element with start element
  26.        
  27.         int temp = nums[start];
  28.         nums[start] = nums[pivotIndex];
  29.         nums[pivotIndex] = temp;
  30.        
  31.         int smaller = start;
  32.        
  33.        
  34.         for(int bigger = start + 1; bigger <= end; bigger++ ) {
  35.             if(nums[bigger] < nums[start]){
  36.                 smaller++;
  37.                 int temp1 = nums[bigger];
  38.                 nums[bigger] = nums[smaller];
  39.                 nums[smaller] = temp1;
  40.             }
  41.         }
  42.        
  43.         //unswap pivot at start with element at smaller
  44.         int temp2 = nums[smaller];
  45.         nums[smaller] = nums[start];
  46.         nums[start] = temp2;
  47.        
  48.         if(smaller == nums.length-k) {result = nums[smaller]; return;}
  49.         else if (nums.length-k < smaller) {
  50.             quickSelect(nums, start, smaller -1, k);
  51.         }
  52.         else if (nums.length-k > smaller) {
  53.             quickSelect(nums, smaller+1, end, k );
  54.         }
  55.        
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement