I have been trying to solve Kth Largest Element in an Array
This is my code:
public static int findKthLargest(int[] nums, int k) {
Queue<Integer> q = new LinkedList<>();
int max = Integer.MIN_VALUE;
for(int i=0; i< nums.length; i++){
if(nums[i]>=max){
max = nums[i];
if(q.size() <k)
q.add(max);
else{
q.poll();
q.add(max);
}
}
}
return q.peek();
}
The main idea behind my code is that I keep storing the maximum values in a queue of length K, and after I iterate over all the values in the array I return the first Item as it's the maximium Kth element.
But it fails on the following testcase: Input: Array = [2, 1] K = 2 -- Expected output: 1 -- My Output: 2
I just don't get it, how is 1 is supposed to be the 2nd largest element in the array? Please correct me if I'm messing anything.