코딩 테스트 풀이 8 - 프린터

배효림·2023년 3월 17일
0

코딩테스트

목록 보기
8/20

✔ 문제

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

💡 접근 방법

우선 앞에서 지속적으로 원소를 꺼내야 한다는 점에서 Linked List 또는 Queue 가 생각이 나는데 그 중 LinkedList 로 접근해보려고 한다. 직관적으로, LinkedList에서 removeFirst로 첫번째 원소를 빼고, 리스트를 순회해가며 우선순위 체크 후 해당 원소보다 더 높은 우선순위를 가진 원소가 없다면 멈추고, 그게 아니라면 리스트 뒤에 해당 원소를 더하고, 그에 맞춰서 우리가 원하는 원소의 위치 또한 업데이트 한다.

⭐ 코드

import java.util.Iterator;
import java.util.LinkedList;

class Solution
{
    public int solution(int[] priorities, int location)
    {
        // 예외 처리
        if (priorities.length == 1)
        {
            return 1;
        }

        // add values to list
        LinkedList<Integer> list = new LinkedList<>();
        for (int priority : priorities)
        {
            list.add(priority);
        }

        int currentLocation = location;
        int answer = 0;

        while (list.size() > 0)
        {
            int currentPriority = list.removeFirst();
            Iterator<Integer> iterator = list.iterator();
            boolean IsPrinted = true;

            while (iterator.hasNext())
            {
                // 대기 목록에 있는 애들보다 priority 가 높은지 판단
                if (currentPriority < iterator.next())
                {
                    list.addLast(currentPriority);
                    IsPrinted = false;
                    break;
                }
            }

            if (IsPrinted)
                answer ++;

            if (IsPrinted && currentLocation == 0)
            {
                break;
            }
            else if (currentLocation == 0)
            {
                currentLocation = list.size() - 1;
            }
            else
            {
                currentLocation -= 1;
            }
        }

        return answer;
    }
}

💻 더 나은 코드 분석

profile
항상 위를 바라보는 프로그래머

0개의 댓글