We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public Student(int id, String name, double cgpa) {
this.id = id;
this.name = name;
this.cgpa = cgpa;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getCGPA() {
return cgpa;
}
@Override
public int compareTo(Student other) {
if (Double.compare(other.cgpa, this.cgpa) != 0) {
return Double.compare(other.cgpa, this.cgpa); // Higher CGPA comes first
} else {
if (!this.name.equals(other.name)) {
return this.name.compareTo(other.name); // Sort by name alphabetically
} else {
return Integer.compare(this.id, other.id); // Sort by ID if names are the same
}
}
}
}
class Priorities {
public List getStudents(List events) {
PriorityQueue pq = new PriorityQueue<>();
int idCounter = 0;
for (String event : events) {
String[] parts = event.split(" ");
String operation = parts[0];
if (operation.equals("ENTER")) {
String name = parts[1];
double cgpa = Double.parseDouble(parts[2]);
int token = Integer.parseInt(parts[3]);
pq.add(new Student(idCounter++, name, cgpa));
} else if (operation.equals("SERVED")) {
pq.poll(); // Remove the highest priority student
}
}
List<Student> result = new ArrayList<>();
while (!pq.isEmpty()) {
result.add(pq.poll());
}
return result;
}
}
public class Solution {
private final static Scanner scan = new Scanner(System.in);
private final static Priorities priorities = new Priorities();
public static void main(String[] args) {
int totalEvents = Integer.parseInt(scan.nextLine());
List<String> events = new ArrayList<>();
while (totalEvents-- != 0) {
String event = scan.nextLine();
events.add(event);
}
List<Student> students = priorities.getStudents(events);
if (students.isEmpty()) {
System.out.println("EMPTY");
} else {
for (Student st: students) {
System.out.println(st.getName());
}
}
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Priority Queue
You are viewing a single comment's thread. Return to all comments →
Answer:> import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.PriorityQueue; class Student implements Comparable { private int id; private String name; private double cgpa;
}
class Priorities { public List getStudents(List events) { PriorityQueue pq = new PriorityQueue<>(); int idCounter = 0;
}
public class Solution { private final static Scanner scan = new Scanner(System.in); private final static Priorities priorities = new Priorities();
}