Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 008eb79

Browse files
committed
Kth largest
1 parent 8b6e7f9 commit 008eb79

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed
Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,25 @@
11
class Solution {
22
public int findKthLargest(int[] nums, int k) {
3-
PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);
4-
for (int e : nums) {
5-
if (minHeap.size() < k) {
6-
minHeap.add(e);
7-
} else {
8-
if (minHeap.peek() < e) {
9-
minHeap.poll();
10-
minHeap.add(e);
11-
}
3+
return find(nums, 0, nums.length - 1, k - 1);
4+
}
5+
6+
private int find(int[] nums, int left, int right, int k) {
7+
int i = left;
8+
int j = right;
9+
int index = nums[left];
10+
while (i < j) {
11+
while (i < j && index >= nums[j]) j--;
12+
if (i < j) {
13+
nums[i++] = nums[j];
14+
}
15+
while (i < j && index <= nums[i]) i++;
16+
if (i < j) {
17+
nums[j--] = nums[i];
1218
}
13-
1419
}
15-
return minHeap.peek();
20+
nums[i] = index;
21+
if (i > k) return find (nums, left, i - 1, k);
22+
else if (i < k) return find(nums, i + 1, right, k);
23+
else return nums[i];
1624
}
1725
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /