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 28 29 30 31 32 33 34 35 36 37 38
| class Solution { public int findKthLargest(int[] nums, int k) { quickSelect(nums, 0, nums.length - 1, k); return nums[k - 1]; }
private int quickSelect(int[] nums, int low, int up, int k) { int pivot = low, left = low + 1, right = up; while (left <= right) { if (nums[left] < nums[pivot] && nums[right] > nums[pivot]) { swap(nums, left, right); left += 1; right -= 1; continue; } if (nums[left] >= nums[pivot]) { left += 1; } if (nums[right] <= nums[pivot]) { right -= 1; } } swap(nums, pivot, right); if (right == k - 1) { return right; } else if (right < k - 1) { return quickSelect(nums, right + 1, up, k); } else { return quickSelect(nums, low, right - 1, k); } }
private void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } }
|