본문 바로가기
알고리즘 이전/프로그래머스 2레벨

프로세스

by hoshi03 2023. 10. 9.

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

 

프로그래머스

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

programmers.co.kr

우선순위 큐를 이용하면 프로세스를 다시 넣는 2번 과정을 거치지 않아도 된다

 

처음에 풀때는 큐를 사용해서 해보려다가 막히고 우선순위 큐를 사용해서 꺼낸값을 초기 인덱스와 꺼낸 값의 인덱스를 비교해서 문제를 푸는식으로 이해했다

import java.util.*;

class Solution {

    public int solution(int[] priorities, int location) {
        int answer = 0;
        //우선순위큐를 내림차순으로 만들어서 큰값부터 나오게 만들어주기
        PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());
        for (int x : priorities) queue.add(x);

        while (!queue.isEmpty()){
            for (int i = 0; i < priorities.length; i++){
                //우선순위 큐 제일 큰 값을 배열과 비교를 해서 
                if (queue.peek() == priorities[i]){
                    if (i == location) return ++answer;
                    queue.poll();
                    answer++;
                }
            }
        }
        return answer;
    }



    public static void main(String[] args) {
        Solution T = new Solution();
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        int[] arr1 = new int[n];
        for (int i = 0; i < n; i++) arr1[i] = in.nextInt();
        System.out.println(T.solution(arr1,m));
    }
}