๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํ”„๋ฆฐํ„ฐ

๋ฐ˜์‘ํ˜•

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํ”„๋ฆฐํ„ฐ

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

๋ฌธ์ œ์ ‘๊ทผ

์ธ์‡„ ๋Œ€๊ธฐ์—ด์—์„œ ์šฐ์„ ์ˆœ์œ„๊ฐ€ ๋†’์€ ๊ฒƒ ๋ถ€ํ„ฐ ์ธ์‡„๋ฅผ ํ•ด์•ผํ•˜๊ณ , location์— ์žˆ๋Š” ์ž‘์—…์ด ๋ช‡๋ฒˆ์งธ๋กœ ์ธ์‡„๋˜๋Š”์ง€๋ฅผ ๊ตฌํ•ด์•ผํ•œ๋‹ค.
๊ทธ๋ž˜์„œ task ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค์–ด ์šฐ์„ ์ˆœ์œ„์™€ ์ฒ˜์Œ ์ฃผ์–ด์ง„ ์ธ๋ฑ์Šค๋ฅผ ์ €์žฅํ•˜๊ณ  ์ด๋ฅผ ํ์— ์ €์žฅ์„ ํ•˜๊ณ ,
๊ฐ€์žฅ ํฐ ์šฐ์„ ์ˆœ์œ„๋ฅผ ํ‘œํ˜„ํ•˜๊ธฐ์œ„ํ•ด์„œ ์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ ์ด์šฉํ•ด์„œ ์ตœ๋Œ€ ํž™์„ ์ด์šฉํ–ˆ๋‹ค.
๊ทธ๋ž˜์„œ ํ•ด๋‹น location์— ์žˆ๋Š” ์ž‘์—…์ด ์ธ์‡„๋  ๋•Œ๊นŒ์ง€ while๋ฌธ์„ ๋Œ๋ฆฌ๋„๋ก ํ–ˆ๋‹ค.

Code

import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Collections;
import java.util.LinkedList;

class Solution {
    class task {
        int priority;
        int index;
        public task(int priority, int index) {
            this.priority = priority;
            this.index = index;
        }
    }
    public int solution(int[] priorities, int location) {
    int answer = 0;
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); // ์ตœ๋Œ€ ํž™ ์ƒ์„ฑ(์šฐ์„ ์ˆœ์œ„๋ฅผ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ €์žฅ)
        Queue<task> print = new LinkedList<>(); //ํ”„๋ฆฐํŠธ ์ธ์‡„ ๋Œ€๊ธฐ์—ด์„ ํ์— ์ €์žฅ
    for(int i = 0; i<priorities.length; i++){
        print.add(new task(priorities[i],i));
        pq.add(priorities[i]);
    }
    while(!print.isEmpty()){
        // ์šฐ์„ ์ˆœ์œ„์— ๋”ฐ๋ผ์„œ ํ”„๋ฆฐํŠธ์˜ ์ธ์‡„๋ฅผ ์ง„ํ–‰
        task cur = print.poll();
        if(cur.priority == pq.peek()){
            answer++;
            if(cur.index == location) break;
            pq.poll();
        } else {
            print.add(cur);
        }
    }
    return answer;
    }
}

์–ด๋ ค์› ๋˜ ์  / ๋ฐฐ์šด ์  / ๋Š๋‚€ ์ 

ํ”„๋ฆฐํŠธ์˜ ์ž‘์—…์„ ํ์™€ ์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ ์ด์šฉํ•ด์„œ ๊ตฌํ˜„ํ•˜์˜€๋‹ค.
์›๋ž˜ ๊ธฐ๋ณธ ์šฐ์„ ์ˆœ์œ„ ํ๋Š” ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋˜๋Š” ์ตœ์†Œ ํž™์ด๊ธฐ ๋•Œ๋ฌธ์— ์ƒ์„ฑํ•  ๋•Œ, Collections.reverseOrder()๋ฅผ ์ด์šฉํ•ด์„œ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ €์žฅ๋˜๋Š” ๋งฅ์Šคํž™์œผ๋กœ ๋ฐ”๊ฟ”์ฃผ์—ˆ๋‹ค.

๋ฐ˜์‘ํ˜•