✔ 프로세스
문제 분석하기
중요도를 최댓값 우선순위 큐에 집어 넣음
만약 최댓값 우선순위와 값이 같다면 꺼내고, 그렇지 않다면 꺼내서 다시 집어넣기
이때 location의 값과 같다면 정답 반환
손으로 풀어보기
- 최댓값 우선순위 큐에 중요도를 저장
- 우선순위가 높은 것이 있는지 확인
- 최댓값 우선순위 큐의 값과 같다면 꺼내기
- 꺼낼 때 실행되는 순서인 answer 증가
- 같지 않다면 꺼내서 다시 집어넣기
- 이때 location에 해당하는 프로세스가 꺼내진다면 실행되는 순서인 answer를 반환
슈도코드 작성하기
priorities(프로세스의 중요도가 순서대로 담긴 배열)
location(알고싶은 프로세스의 위치)
priorityQueue(프로세스 중요도를 담을 최댓값 우선순위 큐)
for(priorities 크기만큼) {
queue에 중요도 담기
}
answer(실행 순서)
while(큐가 빌때까지) {
for(i -> priorities의 크기만큼) {
if(priorities[i]가 가장 우선순위가 크다면) {
priorityQueue.poll
answer 증가
if(i == location) {
return answer
}
}
}
}
return answer
코드 구현하기
/**
* 42587) 프로세스
*/
public class K004_42587 {
// priorities(프로세스의 중요도가 순서대로 담긴 배열)
// location(알고싶은 프로세스의 위치)
public int solution(int[] priorities, int location) {
// priorityQueue(프로세스 중요도를 담을 최댓값 우선순위 큐)
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());
// 중요도 담기
for (int i = 0; i < priorities.length; i++) {
priorityQueue.offer(priorities[i]);
}
// answer(실행 순서)
int answer = 0;
while (!priorityQueue.isEmpty()) {
for (int i = 0; i < priorities.length; i++) {
// priorities[i]가 가장 우선순위가 크다면
if (priorityQueue.peek() == priorities[i]) {
// 프로세스 꺼내기
priorityQueue.poll();
// 실행되므로 answer 증가
answer++;
// 실행되는 프로세스가 location과 같다면
if (i == location) {
// 실행 순서 반환
return answer;
}
}
}
}
return answer;
}
// 테스트 케이스
public static void main(String[] args) {
K004_42587 solution = new K004_42587();
int[] priorities = { 2, 1, 3, 2 };
int location = 2;
int result = solution.solution(priorities, location);
System.out.println(result);
}
}
'Coding Test > Java 알고리즘 실전' 카테고리의 다른 글
[42584] 주식가격 (0) | 2023.11.28 |
---|---|
[42583] 다리를 지나는 트럭 (0) | 2023.11.28 |
[42579] 베스트앨범 (0) | 2023.11.27 |
[42578] 의상 (0) | 2023.11.26 |
[1844] 게임 맵 최단거리 (0) | 2023.11.26 |