운영체제의 역할 중 하나는 컴퓨터 시스템의 자원을 효율적으로 관리하는 것입니다. 이 문제에서는 운영체제가 다음 규칙에 따라 프로세스를 관리할 경우 특정 프로세스가 몇 번째로 실행되는지 알아내면 됩니다.
예를 들어 프로세스 4개 [A, B, C, D]가 순서대로 실행 대기 큐에 들어있고, 우선순위가 [2, 1, 3, 2]라면 [C, D, A, B] 순으로 실행하게 됩니다.
현재 실행 대기 큐(Queue)에 있는 프로세스의 중요도가 순서대로 담긴 배열 priorities와, 몇 번째로 실행되는지 알고싶은 프로세스의 위치를 알려주는 location이 매개변수로 주어질 때, 해당 프로세스가 몇 번째로 실행되는지 return 하도록 solution 함수를 작성해주세요.
| priorities | location | result |
|---|---|---|
| [2, 1, 3, 2] | 2 | 1 |
| [1, 1, 9, 1, 1, 1] | 0 | 5 |
import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
int answer = 1;
PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());
for(int priority : priorities) {
queue.add(priority);
}
while(!queue.isEmpty()){
for(int i=0; i<priorities.length; i++){
if(queue.peek() == priorities[i]){
if(i == location){
return answer;
}
queue.poll();
answer ++;
}
}
}
return answer;
}
}
우선순위 큐를 사용해서 구현했다.
우선순위 큐는 들어가는 순서와는 상관없이 우선순위가 높은 데이터가 먼저 나가는 자료구조이다. (오름차순)
PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());우선 순위가 낮은 데이터가 먼저 나가도록 설정했다. (내림차순) ➡️ [ 3, 2, 2, 1 ]