제가 공부한 내용을 정리하는 블로그입니다.
아직 많이 부족하고 배울게 너무나도 많습니다. 틀린내용이 있으면 언제나 가감없이 말씀해주시면 감사하겠습니다😁
Programmers 알고리즘 고득점 Kit입니다.

포인트

프로세스의 최댓값과 그 갯수를 효율적으로 관리하는게 포인트였습니다. Map으로도 관리할 수 있고, 리스트로도 관리할 수 있겠지만
저는 이 문제에서 우선순위 큐를 사용하였습니다.

소스코드

import java.util.*;

class Solution {
    
    static class Process {
        int priority, index;
        public Process(int priority, int index) {
            this.priority = priority;
            this.index = index;
        }
    }
    
    public int solution(int[] priorities, int location) {
        Queue<Process> processes = new LinkedList<>();
        PriorityQueue<Integer> remainPriority = new PriorityQueue<>(Collections.reverseOrder());
        
        int len = priorities.length;
        
        for(int i = 0; i < len; i++) {
            int priority = priorities[i];
            remainPriority.add(priority);
            processes.add(new Process(priority, i));
        }
        
        int order = 1;
        while(true) {
            Process ready = processes.poll();
            int maxPriority = remainPriority.poll();
            if (maxPriority == ready.priority) {
                if (location == ready.index) {
                    return order;
                } else {
                    order++;
                }
            } else {
                remainPriority.add(maxPriority);
                processes.add(ready);
            }
        }
    }
}

코드 설명

  • static class Process
    우선순위와 고유번호를 저장하기 위해 static class Process를 선언합니다.
  • PriorityQueue<Integer> remainPriority = new PriorityQueue<>(Collections.reverseOrder());
    priority를 저장할 우선순위 큐를 선언합니다.
    • 해당 우선순위큐는 최소 힙이 아닌 최대 힙으로 선언하기 위해 Collections.reverseOrder()을 사용합니다.
  • processes 큐에서 프로세스를 하나씩 꺼내 처리합니다.
  • remainPriority에서 가장 높은 우선순위를 가져옵니다.
  • 현재 프로세스의 우선순위가 가장 높은 우선순위와 같으면:
    • location에 있는 프로세스인지 확인합니다.
    • 맞다면 현재 순서(order)를 반환합니다.
    • 아니라면 실행 순서를 증가시킵니다.
  • 현재 프로세스의 우선순위가 가장 높지 않으면:
    • 프로세스를 다시 큐에 넣고 remainPriority에 추가하여 다음 순서를 준비합니다.

+ Recent posts