Java/코딩테스트

HackerRank - PriorityQueue

Bubbles 2023. 5. 11. 17:00

https://www.hackerrank.com/challenges/java-priority-queue/problem?isFullScreen=true 

 

Java Priority Queue | HackerRank

Leran about Priority Queues in Java

www.hackerrank.com

해당 문제에서는 Student 클래스를 PriorityQueue에 넣기 위해 Student 클래스에서 compareTo(Student o)를 구현하는 것이 관건이었던것 같다.

 

cgpa(내림차순) -> name(알파벳 순) -> id(오름차순) 순으로 정렬하기. 

- cgpa 가 double 형이므로 리턴시 ?연산자로 정수 리턴해주기. 내림차순이므로 o.cgpa - this.cgpa > 0 ? 1 : -1;

- cgpa 같다면, 이름 순 string.compareTo(string2) -> string이 사전순으로 string2보다 앞서면 -1이 리턴된다. 

- 이름 같다면 마지막으로 id 오름차순! this.id - o.id (id는 int형이므로 그냥 이 채로 리턴해주었다) 

 

음수가 앞서면 this가 앞선다고 생각! 

import java.util.*;
class Student implements Comparable<Student> {
    int id;
    String name;
    double cgpa; 
    Student (int id, String name, double cgpa) {
         this.id = id;
         this.name = name;
         this.cgpa = cgpa;
    }
    
    public int getID() {
        return this.id;
    }
    
    public String getName() {
        return this.name;
    }
    
    public double getCGPA() {
        return this.cgpa;
    }
    
    //  CGPA -> alphabet order -> id ascend
    @Override
    public int compareTo(Student o) {
        
        if (this.cgpa != o.cgpa) {
            return (o.cgpa - this.cgpa > 0) ? 1 : -1;
        }
        else {
            if (!this.name.equals(o.name)) {
                return this.name.compareTo(o.name);
            }
            else {
                return this.id - o.id;
            }
        }
    }
 } 
 
 class Priorities {
    PriorityQueue<Student> pq = new PriorityQueue<>();
    
    public List<Student> getStudents(List<String> events) {
        List<Student> students = new ArrayList<>();
        for (String s : events) {
            String[] arr = s.split(" ");
            if (arr[0].equals("SERVED")) {
                if (!pq.isEmpty()) {
                    pq.poll();
                }
            } else {
                double cgpa = Double.parseDouble(arr[2]);
                int id = Integer.parseInt(arr[3]);
                pq.add(new Student(id, arr[1], cgpa));
            }
        }
        while (!pq.isEmpty()) {
            students.add(pq.poll());
        }
        return students;
    }
 }