1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { int[] nums;
public int findKthLargest(int[] nums, int k) { this.nums = nums; int n = nums.length; return quickSelect(0, n - 1, n - k); }
private int quickSelect(int left, int right, int k) { if (left == right) return nums[k]; int x = nums[left + right >> 1], i = left - 1, j = right + 1; while (i < j) { do i++; while (nums[i] < x); do j--; while (nums[j] > x); if (i < j) swap(i, j); } if (k <= j) return quickSelect(left, j, k); else return quickSelect(j + 1, right, k); }
private void swap(int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } }
|