본문 바로가기

알고리즘

프로그래머스 42587번 | 프로세스 문제 풀이 (Java)

문제

 

제출 코드

import java.util.*;

class Solution {
    public int solution(int[] priorities, int location) throws Exception {
        int answer = 0;
        
        Queue<Process> que = new LinkedList<>();
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
        
        for(int i = 0; i < priorities.length; i++) {
            que.add(new Process(priorities[i], i));
            pq.add(priorities[i]);
        }
        
        int count = 0;
        while(!que.isEmpty()) {
            Process current = que.poll();
            if(current.priority == pq.peek()) {
                pq.remove();
                count++;
                if(current.index == location) {                    
                    answer = count;
                    break;
                }
            }
            else {
                que.add(current);
            }
        }
        
        return answer;
    }

    static class Process {
        private  int priority;
        private  int index;

        public Process(int priority, int index) {
            this.priority = priority;
            this.index = index;
        }
        
        public String toString() {
            return "{priority: " + priority + ", index: " + index + "}";
        }
    }   
}

 

 

문제 의도

- 큐의 기본 동작 이해

- 시뮬레이션

 

문제 출처