PriorityQueue in java
It is used as heap and stores element in a natural order(SORTED).
it pops and reads from the starting end .
eX: 1
Problem : To find kth smallest number in array
import java.util.*;
import java.lang.*;
import java.io.*;
class small
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t>0)
{
int n=ab.nextInt();
int i,min;
PriorityQueue<Integer> ptq=new PriorityQueue<Integer>(n);
ptq.clear();
for(i=0;i<n;++i)
{
ptq.add(ab.nextInt());
}
int k=ab.nextInt();
// System.out.print(k);
i=1;
while(i++<k)
{
ptq.poll();
}
System.out.println(ptq.peek());
t--;
}
}
}
it pops and reads from the starting end .
eX: 1
Problem : To find kth smallest number in array
import java.util.*;
import java.lang.*;
import java.io.*;
class small
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t>0)
{
int n=ab.nextInt();
int i,min;
PriorityQueue<Integer> ptq=new PriorityQueue<Integer>(n);
ptq.clear();
for(i=0;i<n;++i)
{
ptq.add(ab.nextInt());
}
int k=ab.nextInt();
// System.out.print(k);
i=1;
while(i++<k)
{
ptq.poll();
}
System.out.println(ptq.peek());
t--;
}
}
}
0 Comments:
Post a Comment