프로그래머스 과제 진행하기

피나코·2023년 4월 2일
0

알고리즘

목록 보기
46/46
post-thumbnail

프로그래머스 과제 진행하기 바로가기

문제 설명

과제를 받은 루는 다음과 같은 순서대로 과제를 하려고 계획을 세웠습니다.

  • 과제는 시작하기로 한 시각이 되면 시작합니다.
  • 새로운 과제를 시작할 시각이 되었을 때, 기존에 진행 중이던 과제가 있다면 진행 중이던 과제를 멈추고 새로운 과제를 시작합니다.
  • 진행중이던 과제를 끝냈을 때, 잠시 멈춘 과제가 있다면, 멈춰둔 과제를 이어서 진행합니다.
    • 만약, 과제를 끝낸 시각에 새로 시작해야 되는 과제와 잠시 멈춰둔 과제가 모두 있다면, 새로 시작해야 하는 과제부터 진행합니다.
  • 멈춰둔 과제가 여러 개일 경우, 가장 최근에 멈춘 과제부터 시작합니다.

과제 계획을 담은 이차원 문자열 배열 plans가 매개변수로 주어질 때, 과제를 끝낸 순서대로 이름을 배열에 담아 return 하는 solution 함수를 완성해주세요.

접근 방식

정렬과 스택 자료구조를 활용하여 풀었다.

먼저 plans배열을 start 시간 순으로 정렬을 해준 다음, 반복을 돌면서 과제를 끝내거나 멈추거나 했다.

내 팁으로는 굳이 시간, 분 이렇게 구분을 두기 보다는 그냥 다 분으로 만들어서 계산해버리면 훨씬 편하다.

최근에 멈춘 과제부터 다시 시작하기에 멈춘 과제들은 스택 자료구조에 넣어야 겠다고 판단하였다.

코드

import java.util.*;

class Solution {    
    public List<String> solution(String[][] plans) {
        List<String> answer = new ArrayList<>();
        
        Node[] myPlans = new Node[plans.length];
        
        for(int i = 0 ; i < plans.length; i++){
            String[] time = plans[i][1].split(":");
            myPlans[i] = new Node(i, 
                                  Integer.parseInt(time[0]) * 60 + Integer.parseInt(time[1]), 
                                  Integer.parseInt(plans[i][2]));
        }
        
        Arrays.sort(myPlans, (o1, o2) -> {return o1.start - o2.start;});
        
        Stack<Node> remain = new Stack<>();
        
        for(int i = 0 ; i < myPlans.length - 1; i++){
            int cur = myPlans[i].start + myPlans[i].playTime;
            int next = myPlans[i+1].start;
            
            if(cur <= next){
                answer.add(plans[myPlans[i].index][0]);
                
                int jjaturi = next - cur;
                while(jjaturi > 0 && !remain.isEmpty()){
                    int del = remain.peek().playTime - jjaturi;
                    remain.peek().playTime = Math.max(0, del);
                    if(del <= 0) {
                        jjaturi = -1 * del;
                        answer.add(plans[remain.pop().index][0]);
                    }else{
                        jjaturi = 0;
                    }
                }
            }else{
                myPlans[i].playTime = (cur - next);
                remain.push(myPlans[i]);
            }
        }
        answer.add(plans[myPlans[myPlans.length - 1].index][0]);
        
        while(!remain.isEmpty()){
            answer.add(plans[remain.pop().index][0]);
        }
        
        return answer;
    }
    
    static class Node{
        int index;
        int start;
        int playTime;
        
        public Node(int index, int start, int playTime){
            this.index = index;
            this.start = start;
            this.playTime = playTime;
        }
        
    }
}

Disscussion

정렬과 스택을 떠올리기 까지는 얼마 안걸렸으나 구현 부분에서 다소 시간이 걸렸다.

특히 while문 코드가 작성하기 복잡했다.

profile
_thisispinako_

0개의 댓글