You are viewing a single comment's thread. Return to all comments →
I think we may optimize little more
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.StringTokenizer; import java.util.PriorityQueue; import java.util.Comparator; class Student { private int id; private String name; private double cgpa; Student(int id, String name, double cgpa) { this.id = id; this.name = name; this.cgpa = cgpa; } Student(String name, double cgpa, int id) { this(id, name, cgpa); } public int getID() { return id; } public String getName() { return name; } public double getCGPA() { return cgpa; } } class MyComparator implements Comparator<Student> { public int compare(Student s1, Student s2) { if (s1.getCGPA() == s2.getCGPA()) { if (s1.getName().equals(s2.getName())) { return s1.getID() - s2.getID(); } return s1.getName().compareTo(s2.getName()); } return s1.getCGPA() > s2.getCGPA() ? -1 : 1; } } class Priorities { public List<Student> getStudents(List<String> events) { List<Student> students = new ArrayList<>(); boolean sorted = false; for (String event : events) { StringTokenizer st = new StringTokenizer(event); switch(st.nextToken()) { case "ENTER": students.add(new Student(st.nextToken(), Double.parseDouble(st.nextToken()), Integer.parseInt(st.nextToken()))); sorted = false; break; case "SERVED": if (!sorted && students.size() > 1) { students.sort(new MyComparator()); sorted = true; } if (!students.isEmpty()) { students.remove(0); } break; } } return students; } } 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()); } } } }
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 →
I think we may optimize little more