프린터

유태형·2022년 3월 31일
0

문제

문제 분석

몇번째로 인쇄되는지 순서가 중요하고 기본적으로 같은 우선순위일땐 앞의 문서가 먼저 출력되므로 큐를 이용해야 합니다.




풀이

초기화

		int answer = 0;
        int print = priorities[location];
        boolean is_print;
        
        Queue<Integer> queue = new LinkedList<>();
        for(int i=0;i<priorities.length;i++){
            queue.add(priorities[i]);
        }

프린트 하고자 하는 문서의 위치와 큐를 초기화 합니다.

인쇄 여부

맨앞에 있는 문서가 가장큰 우선순위를 가지면 인쇄합니다.

			int max = it.next(); //맨앞 최대로 가정
            while(it.hasNext()){
                int temp = it.next();
                
                if(max < temp){ //최대가 아니면
                    max = temp;
                    is_print=false; //인쇄x
                }
            }

문서의 이동

맨앞의 문서가 인쇄가 되었는지, 맨뒤로 이동했는지, 찾는 문서가 맨앞이었는지 여부를 확인하며 조정합니다.

			int first = queue.poll(); //맨 앞고
            location--; //위치 -1
              
            if(is_print){ //최대값이면
                answer++; //출력 +1
                if(first == print && location == -1) //출력값이고 위치가 0이면(인쇄하고자 하는 값이면)
                    break;
            }else{ //최대값이 아니면
                queue.add(first); //맨뒤에 추가
                if(location == -1) //뽑고자하는 값이면
                    location = queue.size()-1; //위치 맨뒤로 해줌
            }
            
        }



코드

import java.util.*;
import java.util.stream.*;

class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        int print = priorities[location];
        boolean is_print;
        
        Queue<Integer> queue = Arrays.stream(priorities).boxed().collect(Collectors.toCollection(LinkedList::new));
        
        while(true){
            Iterator<Integer> it = queue.iterator();
            is_print = true;
            
            int max = it.next(); //맨앞 최대로 가정
            while(it.hasNext()){
                int temp = it.next();
                
                if(max < temp){ //최대가 아니면
                    max = temp;
                    is_print=false; //인쇄x
                }
            }
            
            int first = queue.poll(); //맨 앞고
            location--; //위치 -1
              
            if(is_print){ //최대값이면
                answer++; //출력 +1
                if(first == print && location == -1) //출력값이고 위치가 0이면(인쇄하고자 하는 값이면)
                    break;
            }else{ //최대값이 아니면
                queue.add(first); //맨뒤에 추가
                if(location == -1) //뽑고자하는 값이면
                    location = queue.size()-1; //위치 맨뒤로 해줌
            }
            
        }
        return answer;
    }
}



GitHub

https://github.com/ds02168/Study_Algorithm/blob/master/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4/%EC%9E%90%EB%B0%94/Level2/%ED%94%84%EB%A6%B0%ED%84%B0.java

profile
오늘도 내일도 화이팅!

0개의 댓글

관련 채용 정보