[문제]
운영체제의 역할 중 하나는 컴퓨터 시스템의 자원을 효율적으로 관리하는 것입니다. 이 문제에서는 운영체제가 다음 규칙에 따라 프로세스를 관리할 경우 특정 프로세스가 몇 번째로 실행되는지 알아내면 됩니다.
1. 실행 대기 큐(Queue)에서 대기중인 프로세스 하나를 꺼냅니다.
2. 큐에 대기중인 프로세스 중 우선순위가 더 높은 프로세스가 있다면 방금 꺼낸 프로세스를 다시 큐에 넣습니다. 3. 만약 그런 프로세스가 없다면 방금 꺼낸 프로세스를 실행합니다.
3.1 한 번 실행한 프로세스는 다시 큐에 넣지 않고 그대로 종료됩니다.
예를 들어 프로세스 4개 [A, B, C, D]가 순서대로 실행 대기 큐에 들어있고, 우선순위가 [2, 1, 3, 2]라면 [C, D, A, B] 순으로 실행하게 됩니다.
현재 실행 대기 큐(Queue)에 있는 프로세스의 중요도가 순서대로 담긴 배열 priorities와, 몇 번째로 실행되는지 알고싶은 프로세스의 위치를 알려주는 location이 매개변수로 주어질 때, 해당 프로세스가 몇 번째로 실행되는지 return 하도록 solution 함수를 작성해주세요.
[Algorithm]
1. 큐에 담긴 프로세스의 실행 순서 구하기
2. location 인덱스의 실행 순서 찾기
알고리즘은 생각했는데 구현 방법이 떠오르지 않아서 검색함 ..
[Code]
import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < priorities.length; i++) {
queue.offer(new int[]{priorities[i], i});
}
int executionOrder = 0;
while (!queue.isEmpty()) {
int[] current = queue.poll();
int currentPriority = current[0];
int currentIndex = current[1];
boolean hasHigherPriority = false;
for (int[] process : queue) {
if (process[0] > currentPriority) {
hasHigherPriority = true;
break;
}
}
if (hasHigherPriority) {
queue.offer(current);
}
else {
executionOrder++;
if (currentIndex == location) {
return executionOrder;
}
}
}
return -1;
}
}
1. 큐에 {우선순위, 원래 인덱스) 쌍을 저장
2. 큐가 빌 때까지 반복
- 맨 앞 프로세스 꺼내기
- 현재 프로세스보다 높은 우선 순위가 큐에 있는지 확인
- 더 높은 우선순위가 있으면 맨 뒤로 보내기
- 없으면 실행 (실행 순서 증가)
- 목표 인덱슬 실행 순서 반환
[+ 다른 사람 풀이]
import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
int answer = 1;
PriorityQueue p = new PriorityQueue<>(Collections.reverseOrder());;
for(int i=0; i<priorities.length; i++){
p.add(priorities[i]);
System.out.println(p);
}
System.out.println(p);
while(!p.isEmpty()){
for(int i=0; i<priorities.length; i++){
if(priorities[i] == (int)p.peek()){
if(i == location){
return answer;
}
p.poll();
answer++;
}
}
}
return answer;
}
}
우선순위 큐를 활용한 코드
[+ Plus]
더보기
💡Queue 인터페이스
먼저 넣은 객체가 먼저 빠져나가는 FIFO 자료구조
Queue<E> queue = new LinkedList<E>();
offer : 주어진 객체 삽입
peek : 객체 하나 가져옴, 큐에서 제거 안함
poll : 객체 하나 가져옴, 큐에서 제거
PriorityQueue (우선순위 큐)
저장한 순서와 관계 없이 우선순위에 따라 꺼내는 순서가 정해진 큐
'Algorithm Study' 카테고리의 다른 글
[Java Algorithm] 프로그래머스 Lv.2 _ 올바른 괄호 (0) | 2025.08.19 |
---|---|
[Java Algorithm] 프로그래머스 Lv.1 _ 같은 숫자는 싫어 (0) | 2025.08.18 |
[Java Algorithm] 프로그래머스 Lv.2_ 피로도 (4) | 2025.08.05 |
[Java Algorithm] 프로그래머스 Lv.2_ 카펫 (4) | 2025.08.04 |
[Java Algorithm] 프로그래머스 Lv.2_ 소수 찾기 (2) | 2025.07.31 |