Drawback
Given an integer array nums
and an integer okay
, return the kth
largest aspect within the array.
Observe that it’s the
kth
largest aspect within the sorted order, not the kth distinct aspect.
Instance
Enter: nums = [3,2,1,5,6,4], okay = 2
Output: 5
Strategy 1: Utilizing Sorting
We will use sorting to first kind the nums array in pure order after which return kth aspect from finish i.e n-k th aspect from begin.
Ok index from finish is the same as length-k index from begin
class Resolution {
public int findKthLargest(int[] nums, int okay) {
Arrays.kind(nums);
return nums[nums.length-k];
}
}
Complexity Evaluation
TC: O(N log N)
, the place N
is the dimensions of the enter array
SC: O(1)
Strategy 2: Utilizing Heap
Truly there are a number of sub-approaches if we select to make use of Heap
.
Strategy | Variety of components | variety of ballot |
---|---|---|
Min Heap of measurement N | Min heap to retailer all N components(at most N-Ok minimal components at any given time) |
ballot for N-Ok occasions to get kth largest |
Min Heap of measurement Ok | Min heap to retailer at most Ok components. Including new components after first Ok components are added, we verify if new aspect is larger than heap root(peek) and in that case we delete it first after which add the brand new better aspect, in any other case not | ballot for 1 time and return the polled aspect |
Max Heap of measurement N | Max heap to retailer all N components(at most Ok most components at any given time) |
ballot for Ok occasions to get kth largest |
Min Heap of measurement N
class Resolution {
public int findKthLargest(int[] nums, int okay) {
int n = nums.size;
if (n == 1) {
return nums[0];
}
PriorityQueue<Integer> minHeap = new PriorityQueue();
for(int num: nums){
minHeap.supply(num);
}
int i = 0;
int kThLargest = minHeap.ballot();
whereas (i++ < (n - okay)) {
kThLargest = minHeap.ballot();
}
return kThLargest;
}
}
Min Heap of measurement Ok
import java.util.Arrays;
import java.util.Collections;
//Min Heap of measurement Ok
class Resolution {
public int findKthLargest(int[] nums, int okay) {
int n = nums.size;
if (n == 1) {
return nums[0];
}
PriorityQueue<Integer> minHeap = new PriorityQueue(okay);
for(int i=0; i<okay; i++){
minHeap.supply(nums[i]);
}
for(int i=okay; i<n; i++){
if(minHeap.peek() < nums[i]){
minHeap.ballot();
minHeap.supply(nums[i]);
}
}
return minHeap.ballot();
}
}
Max Heap of measurement N
class Resolution {
public int findKthLargest(int[] nums, int okay) {
int len = nums.size;
if(len == 1){
return nums[0];
}
// Since we're utilizing Max-Heap, we have to kind accordingly
Comparator<Integer> comp = (a,b) -> b.compareTo(a);
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(comp);
// Add all the weather
for(int num: nums){
maxHeap.supply(num);
}
// we have to ballot for k-1 occasions and
// return the following polled aspect
int i = 1;
whereas(i++ < okay){
maxHeap.ballot();
}
return maxHeap.ballot();
}
}