Last active
May 22, 2021 01:53
-
-
Save Ram-1234/b3800233d038ad9b4622057f89e83bee to your computer and use it in GitHub Desktop.
Kth smallest array element using max heap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Example:- | |
input: | |
array size=5 | |
kth number =2 | |
arr[]={9,2,15,3,16} | |
/* package whatever; // don't place package name! */ | |
import java.util.*; | |
import java.lang.*; | |
import java.io.*; | |
/* Name of the class has to be "Main" only if the class is public. */ | |
class Ideone | |
{ | |
public static void main (String[] args) throws java.lang.Exception | |
{ | |
Scanner sc=new Scanner(System.in); | |
int size=sc.nextInt(); | |
int k=sc.nextInt(); | |
int[] arr=new int[size]; | |
for(int i=0;i<size;i++){ | |
arr[i]=sc.nextInt(); | |
} | |
PriorityQueue<Integer> minhip=new PriorityQueue<>((a,b)->b-a); | |
for(int i:arr){ | |
if(!minhip.caontains(i)){ | |
minhip.add(i); | |
} | |
if(minhip.size()>k){ | |
minhip.remove(); | |
} | |
} | |
System.out.println(minhip.remove()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment