-
Notifications
You must be signed in to change notification settings - Fork 2
/
KthLargestElement.java
83 lines (70 loc) · 2.05 KB
/
KthLargestElement.java
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package Leetcode;
import java.util.PriorityQueue;
/**
* @author kalpak
*
* 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.
*
*/
public class KthLargestElement {
public static int findKthLargest(int[] nums, int k) {
if(nums == null || nums.length == 0)
return -1;
int result = 0;
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for(int i = 0; i < nums.length; i++) {
minHeap.offer(nums[i]);
if(minHeap.size() > k)
minHeap.poll();
}
return minHeap.peek();
}
public static int findKthLargestUsingQuickSelect(int[] nums, int k) {
int left = 0;
int right = nums.length - 1;
int result = Integer.MIN_VALUE;
while(true) {
int pivot = partition(nums, left, right);
if(pivot == k - 1) {
result = nums[pivot];
break;
}
if(pivot < k - 1)
left = pivot + 1;
else
right = pivot - 1;
}
return result;
}
private static int partition(int[] nums, int start, int end) {
int pivot = nums[end];
int pIndex = start;
for(int i = start; i < end; i++) {
if(nums[i] >= pivot) { // Sort in descending order
swap(nums, i, pIndex);
pIndex++;
}
}
swap(nums, end, pIndex);
return pIndex;
}
private static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public static void main(String[] args) {
int[] nums = new int[]{3,2,3,1,2,4,5,5,6};
System.out.println(findKthLargest(nums, 4));
}
}