https://github.com/emahtab/kth-largest-element-in-an-array
kth largest element in an array
https://github.com/emahtab/kth-largest-element-in-an-array
heap leetcode problem-solving
Last synced: 15 days ago
JSON representation
kth largest element in an array
- Host: GitHub
- URL: https://github.com/emahtab/kth-largest-element-in-an-array
- Owner: eMahtab
- Created: 2020-02-22T06:43:13.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-02-22T08:20:43.000Z (over 5 years ago)
- Last Synced: 2025-08-17T16:56:48.992Z (3 months ago)
- Topics: heap, leetcode, problem-solving
- Size: 8.79 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# kth-largest-element-in-an-array
## https://leetcode.com/problems/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.
```
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.**
## Implementation 1 : Sorting
```java
class Solution {
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length - k];
}
}
```
## Implementation 2 : Heap
```java
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue minHeap = new PriorityQueue<>();
// just keep k largest elements in the min heap
for (int num: nums) {
if(minHeap.size() < k){
minHeap.add(num);
} else {
if(num > minHeap.peek()) {
minHeap.poll();
minHeap.add(num);
}
}
}
return minHeap.peek();
}
}
```
# References :
https://www.youtube.com/watch?v=3d0ORD8Qnk8