Advertisement
exmkg

Untitled

Jan 12th, 2025
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | None | 0 0
  1. class Solution {
  2.     public int findKthLargest(int[] nums, int k) {
  3.         return quickSelect(nums, 0, nums.length - 1, nums.length - k);
  4.     }
  5.  
  6.     private static int quickSelect(int[] arr, int left, int right, int k) {
  7.         // Take a random pivot from the whole range.
  8.         Random rand = new Random();
  9.         int randIndex = rand.nextInt(left, right + 1);
  10.         swap(arr, left, randIndex);
  11.  
  12.         int pivot = arr[left];
  13.         int storeIndex = left + 1;
  14.         for (int i = left + 1; i <= right; i++) {
  15.             if (arr[i] < pivot) {
  16.                 swap(arr, i, storeIndex);
  17.                 storeIndex++;
  18.             }
  19.         }
  20.         swap(arr, left, storeIndex - 1);
  21.         int l = storeIndex - 2;
  22.         int r = storeIndex;
  23.         while (l >= left && arr[l] == pivot) l--;
  24.         while (r <= right && arr[r] == pivot) r++;
  25.  
  26.         if (l + 1 <= k && k <= r - 1) return arr[k];
  27.         if (k <= l) return quickSelect(arr, left, l, k);
  28.         return quickSelect(arr, r, right, k);
  29.     }
  30.  
  31.     private static void swap(int[] arr, int i, int j) {
  32.         int tmp = arr[i];
  33.         arr[i] = arr[j];
  34.         arr[j] = tmp;
  35.     }
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement