티스토리 뷰

CodingTest

프로그래머스 - 프린터 - Queue - JAVA

기억용블로그 2022. 4. 20. 14:58
728x90

 

import java.util.*;

class Solution {
    //현재 위치와 우선순위를 중복과 구분하기 위해 객체 생성.
    //key가 같으면서도 value가 다른게 필요하기 때문.
    class Pair {
        int index;
        int value;
        
        public Pair(int index, int value) {
            this.index = index;
            this.value = value;
        }
    }
    public int solution(int[] priorities, int location) {
        Queue<Pair> q = new LinkedList<>();
        int answer = 0;
        //큐에 우선순위와 우선순위의 위치 형태로 저장.
        for (int i=0; i<priorities.length; i++) {
            q.add(new Pair(i, priorities[i]));
        }
        //큐가 비어있지 않을때
        while (!q.isEmpty()) {
            //제일 앞의 우선순위를 current에 저장. 아직 꺼내진 않음.
            int current = q.peek().value;
            //아직 제일 큰 우선순위를 찾지 못함.
            boolean flag = false;
            
            //큐의 모든 객체를 돌면서 그전보다 큰 우선순위를 찾는다.
            //가장 맨 앞에 값을 꺼내려면 그뒤에 큰 우선순위가 없어야함.
            for (Pair pair : q) {
                if (pair.value > current) {
                    //찾으면 찾음. 신호하고 종료.
                    flag = true;
                    break;
                }
            }
            //맨 앞에 있는 값이 가장 큰 우선순위가 아니므로 다시 뒤에 넣음.
            if (flag) {
                Pair tmp = q.poll();
                q.add(tmp);
            }
            //맨 앞이 가장 큰 우선순위라면 
            else {
                //answer를 올리고 큐에서 제거.
                answer++;
                Pair pair = q.poll();
                
                //뽑아낸 값의 index가 알고자 하는 값이었다면
                if (pair.index == location) {
                    return answer;
                }
            }
        }
        
        return answer;
    }
}

 

소스코드 : https://easybrother0103.tistory.com/112

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함