DataStructure/List
LinkedList/Queue의 활용 - 프로그래머스 프린터
Lazy_developer
2023. 3. 17. 17:48
문제
https://school.programmers.co.kr/learn/courses/30/lessons/42587?language=java
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 접근
- 초기에 저장되어 있는 위치를 기준으로 내가 원하는 문서를 잡아야 한다. 따라서 초기 상태의 인덱스와 해당 데이터의 우선순위를 하나의 클래스로 묶어 관리하면 편리하다.
- 이후에는 리스트를 순회하면서 맨 처음에 있는 요소보다 더 큰 우선순위를 가진 요소가 존재한다면 뒷쪽으로 보내고 그렇지 않다면 poll 한다. 이때 인덱스가 내가 원하는 인덱스인지 검사하면 끝이다.
import java.util.*;
class Paper{
int priority;
int location;
Paper(int priority, int location){
this.priority = priority;
this.location = location;
}
}
class Solution {
public int solution(int[] priorities, int location) {
int answer = 1;
LinkedList<Paper> printer = new LinkedList<>();
for(int i = 0; i < priorities.length; i++){
printer.addLast(new Paper(priorities[i], i));
}
while(!printer.isEmpty()){
Paper paper = printer.peekFirst();
boolean canPrint = true;
for(Paper otherPaper: printer){
if(otherPaper.priority > paper.priority){
canPrint = false;
break;
}
}
if(canPrint){
if(paper.location == location){
return answer;
} else{
answer++;
printer.pollFirst();
}
} else{
printer.addLast(printer.pollFirst());
}
}
return -1;
}
}