Skip to content

Commit ea4643a

Browse files
solves kth largest element in array in java
1 parent 3982b6d commit ea4643a

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@
172172
| 210 | [Course Schedule II](https://leetcode.com/problems/course-schedule-ii) | | |
173173
| 211 | [Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure) | | |
174174
| 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii) | | |
175-
| 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array) | | |
175+
| 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array) | [![Java](assets/java.png)](src/KthLargestElementInAnArray.java) | |
176176
| 216 | [Combination Sum III](https://leetcode.com/problems/combination-sum-iii) | | |
177177
| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate) | [![Java](assets/java.png)](src/ContainsDuplicate.java) [![Python](assets/python.png)](python/contains_duplicate.py) | |
178178
| 219 | [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii) | [![Java](assets/java.png)](src/ContainsDuplicateII.java) [![Python](assets/python.png)](python/contains_duplicate_ii.py) | |

src/KthLargestElementInAnArray.java

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// https://leetcode.com/problems/kth-largest-element-in-an-array
2+
// T: O(n)
3+
// S: O(1)
4+
5+
public class KthLargestElementInAnArray {
6+
public int findKthLargest(int[] nums, int k) {
7+
int partitionIndex = nums.length - k;
8+
for (int left = 0, right = nums.length - 1, j ; left < right ; ) {
9+
j = partition(nums, left, right);
10+
if (j == partitionIndex) return nums[partitionIndex];
11+
else if (j < partitionIndex) left = j + 1;
12+
else right = j - 1;
13+
}
14+
return nums[partitionIndex];
15+
}
16+
17+
private int partition(int[] array, int left, int right) {
18+
int pivot = array[right], i = left - 1;
19+
for (int j = left ; j < right ; j++) {
20+
if (array[j] < pivot) {
21+
i++;
22+
swap(array, i, j);
23+
}
24+
}
25+
swap(array, i + 1, right);
26+
return i + 1;
27+
}
28+
29+
private void swap(int[] array, int i, int j) {
30+
int temp = array[i];
31+
array[i] = array[j];
32+
array[j] = temp;
33+
}
34+
}

0 commit comments

Comments
 (0)