- 난이도: Lv2
프로그래머스 링크: https://school.programmers.co.kr/learn/courses/30/lessons/176962
풀이 링크(GitHub): hayannn/CodingTest_Java/프로그래머스/2/과제 진행하기
풀이 시간 : 45분
입력
스택
과제 처리
반환
import java.util.*;
class Solution {
static class Task {
String name;
int start;
int duration;
Task(String name, int start, int duration) {
this.name = name;
this.start = start;
this.duration = duration;
}
}
public String[] solution(String[][] plans) {
int n = plans.length;
List<Task> tasks = new ArrayList<>();
for (String[] plan : plans) {
String name = plan[0];
String[] time = plan[1].split(":");
int start = Integer.parseInt(time[0]) * 60 + Integer.parseInt(time[1]);
int duration = Integer.parseInt(plan[2]);
tasks.add(new Task(name, start, duration));
}
tasks.sort(Comparator.comparingInt(t -> t.start));
Stack<Task> stack = new Stack<>();
List<String> answer = new ArrayList<>();
for (int i = 0; i < n; i++) {
Task curr = tasks.get(i);
int nextStart = (i < n - 1) ? tasks.get(i + 1).start : Integer.MAX_VALUE;
stack.push(new Task(curr.name, curr.start, curr.duration));
int gap = nextStart - (curr.start);
while (!stack.isEmpty() && gap > 0) {
Task top = stack.pop();
if (top.duration <= gap) {
answer.add(top.name);
gap -= top.duration;
} else {
top.duration -= gap;
stack.push(top);
break;
}
}
}
while (!stack.isEmpty()) {
answer.add(stack.pop().name);
}
return answer.toArray(new String[0]);
}
}
import java.util.*;
class Solution {
static class Task implements Comparable<Task> {
String name;
int start;
int duration;
Task(String name, int start, int duration) {
this.name = name;
this.start = start;
this.duration = duration;
}
@Override
public int compareTo(Task o) {
return this.start - o.start;
}
}
public String[] solution(String[][] plans) {
PriorityQueue<Task> pq = new PriorityQueue<>();
for (String[] plan : plans) {
String[] time = plan[1].split(":");
int start = Integer.parseInt(time[0]) * 60 + Integer.parseInt(time[1]);
pq.add(new Task(plan[0], start, Integer.parseInt(plan[2])));
}
List<String> answer = new ArrayList<>();
List<Task> paused = new ArrayList<>();
int now = 0;
while (!pq.isEmpty()) {
Task curr = pq.poll();
now = Math.max(now, curr.start);
// 다음 과제 시작 전까지 현재 과제 끝낼 수 있는지 확인
int nextStart = pq.isEmpty() ? Integer.MAX_VALUE : pq.peek().start;
if (now + curr.duration <= nextStart) {
now += curr.duration;
answer.add(curr.name);
// 남은 시간 동안 멈춘 과제 이어서 처리
while (!paused.isEmpty() && now < nextStart) {
Task last = paused.remove(paused.size() - 1);
if (now + last.duration <= nextStart) {
now += last.duration;
answer.add(last.name);
} else {
last.duration -= (nextStart - now);
paused.add(last);
now = nextStart;
break;
}
}
} else {
// 끝내지 못하면 남은 시간만큼만 진행하고 멈추기
curr.duration -= (nextStart - now);
paused.add(curr);
now = nextStart;
}
}
// 멈춘 과제 이어서 처리
for (int i = paused.size() - 1; i >= 0; i--) {
answer.add(paused.get(i).name);
}
return answer.toArray(new String[0]);
}
}