Movatterモバイル変換


[0]ホーム

URL:


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

Commitea4643a

Browse files
solves kth largest element in array in java
1 parent3982b6d commitea4643a

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

‎README.md

Lines changed: 1 addition & 1 deletion
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

Lines changed: 34 additions & 0 deletions
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+
publicclassKthLargestElementInAnArray {
6+
publicintfindKthLargest(int[]nums,intk) {
7+
intpartitionIndex =nums.length -k;
8+
for (intleft =0,right =nums.length -1,j ;left <right ; ) {
9+
j =partition(nums,left,right);
10+
if (j ==partitionIndex)returnnums[partitionIndex];
11+
elseif (j <partitionIndex)left =j +1;
12+
elseright =j -1;
13+
}
14+
returnnums[partitionIndex];
15+
}
16+
17+
privateintpartition(int[]array,intleft,intright) {
18+
intpivot =array[right],i =left -1;
19+
for (intj =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+
returni +1;
27+
}
28+
29+
privatevoidswap(int[]array,inti,intj) {
30+
inttemp =array[i];
31+
array[i] =array[j];
32+
array[j] =temp;
33+
}
34+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp