-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthLargestElementinanArray0215.java
More file actions
56 lines (43 loc) · 1.15 KB
/
KthLargestElementinanArray0215.java
File metadata and controls
56 lines (43 loc) · 1.15 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
/**
* µÚK´óÔªËØ
*/
public class KthLargestElementinanArray0215 {
public static void main(String[] args) {
int nums[] = {3,2,1,5,6,4};
findKthLargest(nums, 2);
}
// ===============
public static int findKthLargest(int[] nums, int k) {
int i = quickSelect(nums, 0, nums.length-1, k);
//System.out.println(i);
return i;
}
private static int quickSelect(int[] nums, int start, int end, int k) {
int i = start;
int j = end;
int tmp = nums[j];
while (i < j) {
while (i < j && nums[i] > tmp) {
i++;
}
nums[j] = nums[i];
while (i < j && nums[j] <= tmp) {
j--;
}
nums[i] = nums[j];
}
nums[i] = tmp;
if (k == i+1) {
return nums[i];
}
if (k > i+1) {
int result = quickSelect(nums, i+1, end, k);
return result;
}else if (k < i+1) {
int result = quickSelect(nums, start, i-1, k);
return result;
}else{
return -1;
}
}
}