https://school.programmers.co.kr/learn/courses/30/lessons/176962
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
문제 풀이
1. 시간을 비교하기 쉽게 시간 -> 분으로 환산하여 배열 정렬
2. 배열을 돌면서 현재 과제와 이후 과제의 시간 텀을 계산 (nextStart - curTotal)
3. 현재 과제 시간 + 완료 시간 (curTotal) 이 이후 과제의 시작시간 (nextStart) 을 넘어선다면 중간에 멈춰 stack 삽입
4. 아니라면(현재 과제를 텀 안에 다 끝낼 수 있다면) 중간에 멈춘 과제들을 스택에서 꺼내어 계산
5. 완료된 과제들은 List 에 삽입하고 마지막 과제, 스택에 남은 과제 순으로 마지막에 추가
어려웠던 점
1. int <-> String 파싱을 하루종일 해서 괴로웠다. 다음엔 객체를 만들어서 해보자
2. 중간 while 문 안에서 stack.isEmpty() 확인을 안해서 테케에서 런타임 오류가 났다 언제나 확인하자
3. else {
work[2] = Integer.toString(time - remain);
stack.push(work);
remain = 0;
} 이 부분에서 remain 을 먼저 0으로 만들고 계산하는 바람에 테케 틀림.. 바보냐
4. if(remain - time >= 0) {
list.add(work[0]);
remain -= time;
} 여기서도 remain 만 배주고 list에 work를 추가 안해서 틀림.. 아진짜
import java.util.*;
class Solution {
public String[] solution(String[][] plans) {
List<String> list = new ArrayList<>();
Stack<String[]> stack = new Stack<>();
for(String[] p : plans) {
String[] time = p[1].split(":");
int minutes = Integer.parseInt(time[0]) * 60 + Integer.parseInt(time[1]);
p[1] = Integer.toString(minutes);
}
Arrays.sort(plans, (a, b) -> {
return Integer.parseInt(a[1]) - Integer.parseInt(b[1]);
});
for(int i = 1; i < plans.length; i ++) {
String[] cur = plans[i - 1];
String[] next = plans[i];
int curTotal = Integer.parseInt(cur[1]) + Integer.parseInt(cur[2]);
int nextStart = Integer.parseInt(next[1]);
if(curTotal <= nextStart) { // 현재 과제를 한번에 다 했을 때 다음 것 시간에 아직 못미친다면 (한번에 완료)
list.add(cur[0]);
if(nextStart - curTotal > 0) { // 다 하고도 시간이 남으면
int remain = nextStart - curTotal;
while(remain > 0 && !stack.isEmpty()) { // stack에 들어가있는 과제 하기
String[] work = stack.pop();
int time = Integer.parseInt(work[2]);
if(remain - time >= 0) {
list.add(work[0]);
remain -= time;
}
else {
work[2] = Integer.toString(time - remain);
stack.push(work);
remain = 0;
}
}
}
} else { // 중간에 다음 과제로 넘어가야 할 때
int cap = nextStart - Integer.parseInt(cur[1]);
cur[2] = Integer.toString(Integer.parseInt(cur[2]) - cap);
stack.push(cur);
}
}
// 마지막 거 List에 넣고, stack 순서대로 list
list.add(plans[plans.length - 1][0]);
while(!stack.isEmpty()) {
list.add(stack.pop()[0]);
}
return list.toArray(new String[list.size()]);
}
}'알고리즘 > 프로그래머스' 카테고리의 다른 글
| 프로그래머스 시소 짝꿍 자바 JAVA 풀이 (0) | 2025.05.13 |
|---|---|
| 프로그래머스 파일명 정렬 JAVA 자바 풀이 (0) | 2025.03.26 |
| 프로그래머스 뒤에 있는 큰 수 찾기 (0) | 2023.08.29 |
| 프로그래머스 다음 큰 숫자 자바 java 풀이 (0) | 2022.11.11 |
| 프로그래머스 더 맵게 자바 풀이 (0) | 2022.06.09 |