[프로그래머스] LEVEL2 프로세스 JAVA

Pixel Dophin·2023년 7월 25일
0

프로그래머스

목록 보기
27/55

프로세스

문제링크

  1. 실행 대기 큐(Queue)에서 대기중인 프로세스 하나를 꺼냅니다.
  2. 큐에 대기중인 프로세스 중 우선순위가 더 높은 프로세스가 있다면 방금 꺼낸 프로세스를 다시 큐에 넣습니다.
  3. 만약 그런 프로세스가 없다면 방금 꺼낸 프로세스를 실행합니다.
    3.1 한 번 실행한 프로세스는 다시 큐에 넣지 않고 그대로 종료됩니다.

풀이

실행대기 큐를 위해 queue를 만들었고, 대기 중인 프로세스에 우선순위가 높은 프로세스가 있는 지 확인하기 위해 Priority queue를 만들었다.
이후 조건에 맞춰 우선 순위가 높은 프로세스가 존재한다면 꺼낸 큐를 다시 넣었고, 만약 없다면 그대로 꺼내서 실행하며, 현재 실행한 Process의 loc이 찾고자하는 location인지를 확인하여 문제를 풀었다.

코드

import java.util.*;

class Solution {
    public class Process {
        int loc;
        int priority;
        
        public Process (int loc, int priority){
            this.loc = loc;
            this.priority = priority;
        }
    }
    public int solution(int[] priorities, int location) {
        int answer = 0;
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
        Queue<Process> queue = new ArrayDeque<>();
        
        for (int i = 0; i < priorities.length; i++) {
            int num = priorities[i];
            queue.offer(new Process(i, num));
            pq.add(num);
        }
        
       while(!pq.isEmpty()) {
           // 대기 중 프로세스 꺼내기
           Process cur = queue.poll();
           
           // 대기 중 프로세스 중 우선순위가 더 높은 프로세스가 있는 지 확인
           if (pq.peek() > cur.priority) {
               queue.add(cur);
           } else {
               pq.poll();
               answer++;
               if (cur.loc == location){
                   return answer;
               }
           }
		}
        return answer;
    }
}
profile
안녕 👋 성장하고픈 개발자 💻 입니다

0개의 댓글

관련 채용 정보