-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindKthElement.java
More file actions
61 lines (50 loc) · 1.4 KB
/
Copy pathFindKthElement.java
File metadata and controls
61 lines (50 loc) · 1.4 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
215. Kth Largest Element in an Array
Medium
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
*/
package dc;
public class FindKthElement {
public static int findKthLargest(int[] nums, int k) {
if (nums == null || nums.length < k) {
return -1;
}
return findKth(nums, 0, nums.length - 1, k);
}
private static int findKth(int[] nums, int left, int right, int k) {
int pivot = nums[left];
int i = left + 1;
int j = right;
while (i <= j) {
while (i <= j && nums[j] >= pivot) {
j--;
}
while (i <= j && nums[i] <= pivot) {
i++;
}
if (i >= j) {
break;
}
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
nums[left] = nums[j];
nums[j] = pivot;
if (j == nums.length - k) {
return pivot;
} else if (j > (nums.length - k)) {
return findKth(nums, left, j - 1, k);
} else {
return findKth(nums, j + 1, right, k);
}
}
}