MrainW's Home

All things come to those who wait!

0%

LeetCode 215. Kth Largest Element in an Array

Question

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

https://leetcode.com/problems/kth-largest-element-in-an-array/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int findKthLargest(int[] nums, int k) {
//shuffle(nums);
//divide(nums, 0, nums.length - 1, k);
//return nums[nums.length - k];
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int x : nums){
if (heap.size() < k || x >= heap.peek()){
heap.offer(x);
}
if (heap.size() > k) {
heap.poll();
}
}
return heap.peek();
}

Complexity:

Time complexity: O(nlog(k))

Space complexity: O(k)

Welcome to my other publishing channels