[Java 큐] 프로그래머스 - 프린터

gonudayo·2021년 8월 14일
0
post-thumbnail

Cpp와 조금씩 미묘하게 달라, 적응이 필요하다.

풀이

  1. 번호와 중요도로 이루어진 객체를 큐에 담는다.
  2. 현재 중요도 보다 큰 중요도가 있으면 뒤로 미룬다.
    2-1. 없으면 제거한다.
    이때, 요청한 번호와 현재 번호가 동일한 경우,
    전체 문서 개수 - 남은 문서 를 하면 현재 몇 번째인지 리턴할 수 있다.

전체코드

import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        Queue<Pair> q = new LinkedList<>();
        
        for (int i = 0; i < priorities.length; i++) {
			q.offer(new Pair(i, priorities[i]));
		}
        
        while(!q.isEmpty()) {
            boolean flag = false;
            int prio = q.peek().priority;
            
            for(Pair p : q) {
                if(prio < p.priority) {
                    flag = true;
                }
            }
            
            if(flag) {
                q.offer(q.poll());
                answer++;
            }
            else {
                if(q.poll().location == location) return priorities.length - q.size();
            }
        }

        return answer;
    }
}
class Pair{
	int location;
	int priority;
	Pair(int location,int priority){
		this.location = location;
		this.priority = priority;
	}
}

객체를 큐에 담기

class Solution {
    public int solution(int[] priorities, int location) {
        Queue<Pair> q = new LinkedList<>();
        
        for (int i = 0; i < priorities.length; i++) {
			q.offer(new Pair(i, priorities[i]));
		}
    }
}

class Pair{
	int location;
	int priority;
	Pair(int location,int priority){
		this.location = location;
		this.priority = priority;
	}
}

Pair라는 클래스를 만들어 (location, priority) 구조로 큐에 담는다.

중요도 비교하기

while(!q.isEmpty()) {
	boolean flag = false;
    	int prio = q.peek().priority; //현재 중요도
        
        for(Pair p : q) { 
        if(prio < p.priority) { //현재 중요도 보다 높은 중요도가 있을 경우
        	flag = true;
        	}
        }
        
        if(flag) { //맨앞의 값을 뒤로 옮긴다
        	q.offer(q.poll());
        	answer++;
        }
        else { //맨앞의 값을 없앤다. 만약, 요청한 번호라면 리턴
        	if(q.poll().location == location) return priorities.length - q.size();
        }
}
profile
초신성 백엔드 개발자

0개의 댓글