알고리즘/스택 큐

프로그래머스 - 프로세스(Java)

연향동큰손 2025. 1. 2. 15:47

 

처음에는 LinkedList를 이용하여 해결하려고 했는데 쉽지 않았다.

다른 사람들의 풀이를 확인해보니 우선순위 큐를 이용하여 쉽게 해결할 수 있다는 것을 알게 되었다.

 

우선순위 큐
//낮은 숫자가 우선 순위인 int 형 우선순위 큐 선언
PriorityQueue<Integer> priorityQueueLowest = new PriorityQueue<>();

//높은 숫자가 우선 순위인 int 형 우선순위 큐 선언
PriorityQueue<Integer> priorityQueueHighest = new PriorityQueue<>(Collections.reverseOrder());

 

이 문제 에서는 우선순위가 높은 프로세스가 먼저 처리 되어야 하므로 높은 숫자가 우선 순위인 우선순위 큐를 사용해야 한다.

PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());

 

<우선순위 탐색>

while(!pq.isEmpty()) {
			for(int i=0; i<priorities.length; i++) {
				if(priorities[i] == pq.peek()) {
					pq.poll();
					answer++;
					if(i == location)
						return answer;
				}
			}
		}

priorities배열을 순회 하면서 우선순위가 가장 높은 pq.peek()값과 같을때 그게 location의 위치와 동일하면 answer를 리턴해주고 위치가 location과 다르다면 pq.poll()을 이용해 다음 우선순위를 탐색한다.

 

 

<전체 코드>

import java.util.*;

class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
		
		for(int num : priorities) {
			pq.add(num);
		}
		while(!pq.isEmpty()) {
			for(int i=0; i<priorities.length; i++) {
				if(priorities[i] == pq.peek()) {
					pq.poll();
					answer++;
					if(i == location)
						return answer;
				}
			}
		}  
        return answer;
    }
}