과제를 받은 루는 다음과 같은 순서대로 과제를 하려고 계획을 세웠습니다.
과제 계획을 담은 이차원 문자열 배열 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;
}
}
}
정렬과 스택을 떠올리기 까지는 얼마 안걸렸으나 구현 부분에서 다소 시간이 걸렸다.
특히 while문 코드가 작성하기 복잡했다.