프로그래머스 LV.2 프린터

래우기·2021년 11월 14일
1

프로그래머스 LV.2

목록 보기
1/6
post-thumbnail

1. 문제 링크

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

2. 풀이

  1. Work 클래스를 사용하여 요청 순위와 우선 순위를 저장할 수 있도로 구성했다.
  2. 인쇄 대기 목록의 앞 뒤에서 연산이 발생하므로 Deque를 사용했다.
  3. 작업을 꺼낸 뒤에, 꺼낸 작업보다 우선순위가 높은 작업이 있는지 확인하는 작업은 Iterator를 사용했다.

3. 코드

public class Solution {

    static class Work {
        int no;
        int priority;

        public Work(int no, int priority) {
            super();
            this.no = no;
            this.priority = priority;
        }

    }

    static Deque<Work> q = new ArrayDeque<>();

    public int solution(int[] priorities, int location) {
        int answer = 1;
        for (int i = 0; i < priorities.length; i++) {
            q.add(new Work(i, priorities[i]));
        }

        while (!q.isEmpty()) {
            Work now = q.poll();
            Iterator<Work> iter = q.iterator();
            while (iter.hasNext()) {
                // now 보다 우선순위가 높은 작업이 있으면 now 를 맨 뒤에 넣고 마침
                if (iter.next().priority > now.priority) {
                    q.addLast(now);
                    break;
                }
            }
            // 끝까지 돌지않았다면 now 를 인쇄해야한다는 것
            if (!iter.hasNext()) {
                if (now.no == location)
                    break;
                else
                    ++answer;
            }
        }

        return answer;
    }
}

4. 채점 결과

5. 느낀 점

  1. Iterator의 사용법을 익히자!
  2. Iterator<콜렉션에 담긴 형태> iter = 콜렉션.iterator();
  3. Iterator를 통해 객체에 접근하고 싶다면, iterator.hasNext().xxx;
profile
지금 당장 시작해

0개의 댓글