Algorithm/Programmars

[JAVA] Lv2. 프로세스 - 프로그래머스

mopipi 2023. 12. 14. 00:24
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/42587

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


  • 실행 대기 큐에서 프로세스 하나 꺼냄
  • 프로세스의 우선순위 확인
    • 우선 순위가 제일 높지 않은 경우 : 다시 큐에 넣음(뒤에)
    • 우선 순위가 제일 높은 경우 : 프로세스 실행 -> 종료
  • idx == location인 프로세스의 실행 순서 return
우선 순위가 필드인 프로세스 선언 + PriorityQueue 사용 => 테스트 케이스 틀림
→  PriorityQueue의 정렬 방식은 부모 노드와 비교해 우선 순위가 높은 경우 swap하는 방식이므로 우선순위가 같은 경우 어떤 순서로 정렬될지 보장할 수 없음
→ 중요도는 별도로 분리해 사용하고, 큐 방식 그대로 poll, add를 반복하자
  • 중요도는 ArrayList에 넣은 후 내림차순 정렬해준 뒤, remove(0)할 때마다 재정렬해주는 방법도 있지만 우선순위 큐 그대로 사용함
import java.util.*;

class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
        Queue<Process> queue = new LinkedList<>();
        for (int i = 0; i < priorities.length; i++) {
            pq.add(priorities[i]);
            queue.add(new Process(i, priorities[i]));
        }
        while (!queue.isEmpty()) {
            Process p = queue.poll();
            if(pq.peek() == p.priority){
                pq.poll();
                answer++;
                if(p.idx == location) break;
                continue;
            }
            queue.add(p);
        }
        return answer;
    }
    private class Process{
        int idx;
        int priority;
        public Process(int idx, int pro){
            this.idx = idx;
            this.priority = pro;
        }
    }
}
반응형