|
1 | 1 | class Solution { |
2 | 2 | public int findKthLargest(int[] nums, int k) { |
3 | | - if (nums == null || nums.length == 0) { |
4 | | - return 0; |
5 | | - } |
6 | | - |
7 | | - int low = 0, high = nums.length - 1; |
8 | 3 | k = nums.length - k; |
9 | | - |
10 | | - while (low < high) { |
11 | | - int position = quickSelect(nums, low, high); |
12 | | - |
13 | | - if (position == k) { |
14 | | - break; |
15 | | - } else if (position < k) { |
16 | | - low = position + 1; |
17 | | - } else { |
18 | | - high = position - 1; |
19 | | - } |
20 | | - } |
21 | | - |
22 | | - return nums[k]; |
| 4 | + return quickSelect(nums, 0, nums.length - 1, k); |
23 | 5 | } |
24 | 6 |
|
25 | | - private int quickSelect(int[] nums, int low, int high) { |
| 7 | + private int quickSelect(int[] nums, int low, int high, int k) { |
26 | 8 | int idx = low, pivot = high; |
27 | | - int pivot_value = nums[pivot]; |
28 | 9 |
|
29 | 10 | for (int i = low; i < high; i++) { |
30 | | - if (nums[i] < pivot_value) { |
| 11 | + if (nums[i] <= nums[pivot]) { |
31 | 12 | swap(nums, i, idx); |
32 | 13 | ++idx; |
33 | 14 | } |
34 | 15 | } |
35 | 16 |
|
36 | | - swap(nums, idx, high); |
37 | | - return idx; |
| 17 | + swap(nums, idx, pivot); |
| 18 | + |
| 19 | + if (idx == k) { |
| 20 | + return nums[idx]; |
| 21 | + } else if (idx < k) { |
| 22 | + return quickSelect(nums, idx + 1, high, k); |
| 23 | + } else { |
| 24 | + return quickSelect(nums, low, idx - 1, k); |
| 25 | + } |
38 | 26 | } |
39 | 27 |
|
40 | 28 | private void swap(int[] nums, int i, int j) { |
41 | 29 | int temp = nums[i]; |
42 | 30 | nums[i] = nums[j]; |
43 | 31 | nums[j] = temp; |
44 | | - return; |
45 | 32 | } |
46 | 33 | } |
0 commit comments