Skip to content
This repository has been archived by the owner on Oct 2, 2021. It is now read-only.

Create Median Priority Queue.java #122

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions Java/Median Priority Queue.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import java.io.*;
import java.util.*;

public class Main {

public static class MedianPriorityQueue {
PriorityQueue<Integer> left;
PriorityQueue<Integer> right;

public MedianPriorityQueue() {
left = new PriorityQueue<>(Collections.reverseOrder());
right = new PriorityQueue<>();
}

public void add(int val) {
// write your code here
if(right.size() >0 && val > right.peek()){
right.add(val);
}else{
left.add(val);
}
if(left.size() - right.size() ==2){
right.add(left.remove());
}else if(right.size() - left.size() == 2){
left.add(right.remove());
}

}

public int remove() {
// write your code here
if(this.size()==0){
System.out.println("Underflow");
return -1;
}else if(left.size() >= right.size()){
return left.remove();
}else{
return right.remove();
}

}

public int peek() {
// write your code here
if(this.size() ==0){
System.out.println("Underflow");
return -1;
}else if(left.size() >= right.size()){
return left.peek();
}else{
return right.peek();
}
}

public int size() {
// write your code here
return left.size() + right.size();
}
}

public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
MedianPriorityQueue qu = new MedianPriorityQueue();

String str = br.readLine();
while (str.equals("quit") == false) {
if (str.startsWith("add")) {
int val = Integer.parseInt(str.split(" ")[1]);
qu.add(val);
} else if (str.startsWith("remove")) {
int val = qu.remove();
if (val != -1) {
System.out.println(val);
}
} else if (str.startsWith("peek")) {
int val = qu.peek();
if (val != -1) {
System.out.println(val);
}
} else if (str.startsWith("size")) {
System.out.println(qu.size());
}
str = br.readLine();
}
}
}