[JAVA 문제 풀이] 321. 프로세스

프로그래머스 (42587)
Stupefyee's avatar
Jun 16, 2025
[JAVA 문제 풀이] 321. 프로세스
notion image
 

내가 작성한 코드

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 order = 0; // 실행된 순서 while (!queue.isEmpty()) { int[] current = queue.poll(); // 현재 문서 // 현재보다 높은 우선순위가 큐에 존재하는지 확인 boolean hasHigher = false; // 큐를 순회하여 현재 문서보다 높은 우선순위가 있는지 확인 for (int[] q : queue) { if (q[0] > current[0]) { hasHigher = true; break; } } // 현재 문서보다 높은 우선순위가 있다면 if (hasHigher) { queue.offer(current); // 다시 뒤로 보냄 } else { // 실행 order++; if (current[1] == location) { return order; } } } return -1; // 이론상 도달하지 않음 } }
 

다른 사람의 코드

import java.util.*; class Solution { public int solution(int[] priorities, int location) { int answer = 0; // 인쇄 순서를 저장할 변수 int l = location; // 내가 찾는 문서의 현재 위치 Queue<Integer> que = new LinkedList<Integer>(); // 인쇄 대기 문서들의 우선순위를 저장할 큐 // 모든 문서를 큐에 추가 for (int i : priorities) { que.add(i); } Arrays.sort(priorities); // 우선순위 배열을 오름차순 정렬 (가장 큰 값이 마지막에 위치) int size = priorities.length - 1; // 가장 높은 우선순위의 인덱스 // 큐가 빌 때까지 반복 while (!que.isEmpty()) { Integer i = que.poll(); // 큐에서 맨 앞 문서를 꺼냄 // 꺼낸 문서가 현재 남아있는 문서 중 가장 높은 우선순위라면 if (i == priorities[size - answer]) { answer++; // 인쇄 순서 증가 l--; // 내 문서 위치도 한 칸 앞으로 이동 if (l < 0) // 내가 찾는 문서가 인쇄된 경우 break; // 반복 종료 } else { que.add(i); // 우선순위가 아니면 다시 큐 뒤에 추가 l--; // 내 문서 위치도 한 칸 앞으로 이동 if (l < 0) // 내 문서가 맨 뒤로 간 경우 l = que.size() - 1; // 위치를 큐의 맨 뒤로 갱신 } } return answer; // 내 문서가 몇 번째로 인쇄되는지 반환 } }
 
Share article

stupefyee