Kth Largest Element in an Array

Kth Largest Element in an Array

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.

Solution1

Sort

O(nlog(n))

1
2
3
4
5
6
7
8
9
10
11
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>(k);

for (int num : nums) {
pq.offer(num);
if (pq.size() > k) {
pq.poll();
}
}
return pq.peek();
}

Solution2

Min Heap

O(nlog(k))

1
2
3
4
5
6
7
8
9
10
11
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>(k);

for (int num : nums) {
pq.offer(num);
if (pq.size() > k) {
pq.poll();
}
}
return pq.peek();
}

Solution3

Quick Sort

O(n)

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
public int findKthLargest(int[] nums, int k) {
if (k < 1 || nums == null) {
return 0;
}
return getKth(nums.length - k +1, nums, 0, nums.length - 1);
}

private int getKth(int k, int[] nums, int start, int end) {
int pivot = nums[end];
int left = start;
int right = end;

while (true) {
while (nums[left] < pivot && left < right) {
left++;
}

while (nums[left] >= pivot && left < right) {
right--;
}

if (left == right) {
break;
}
swap(nums, left, right);
}

swap(nums, left, end);
if (k == left + 1) {
return pivot;
} else if (k < left + 1) {
return getKth(k, nums, start, left - 1);
} else {
return getKth(k, nums, left + 1, end);
}
}

private void swap(int[] nums, int n1, int n2) {
int tmp = nums[n1];
nums[n1] = nums[n2];
nums[n2] = tmp;
}