
| 문제 | 레벨 | 정답률 |
|---|---|---|
| 기능개발 | Lv.2 | 63% |
프로그래머스 팀에서는 기능 개선 작업을 수행 중입니다. 각 기능은 진도가 100%일 때 서비스에 반영할 수 있습니다.
또, 각 기능의 개발속도는 모두 다르기 때문에 뒤에 있는 기능이 앞에 있는 기능보다 먼저 개발될 수 있고, 이때 뒤에 있는 기능은 앞에 있는 기능이 배포될 때 함께 배포됩니다.
먼저 배포되어야 하는 순서대로 작업의 진도가 적힌 정수 배열 progresses와 각 작업의 개발 속도가 적힌 정수 배열 speeds가 주어질 때 각 배포마다 몇 개의 기능이 배포되는지를 return 하도록 solution 함수를 완성하세요.
import java.util.*;
class Solution {
class Progress{
int percentage;
int speed;
public Progress(int percentage, int speed){
this.percentage = percentage;
this.speed = speed;
}
public int remainingDays(){
return (int) Math.ceil((100.0-percentage) / (double) speed);
}
}
public int[] solution(int[] progresses, int[] speeds) {
Queue<Progress> queue = new LinkedList<>();
List<Integer> answerList = new ArrayList<>();
for(int i = 0; i<progresses.length; i++){
queue.offer(new Progress(progresses[i], speeds[i]));
}
while(!queue.isEmpty()){
int completedTasks = 0;
int remainingDays = queue.peek().remainingDays();
while(!queue.isEmpty() && queue.peek().remainingDays() <= remainingDays){
queue.poll();
completedTasks++;
}
answerList.add(completedTasks);
}
int[] answer = new int[answerList.size()];
for(int i = 0; i<answerList.size(); i++){
answer[i] = answerList.get(i);
}
return answer;
}
}
import java.util.*;
class Solution {
class Progress{
int percentage;
int speed;
public Progress(int percentage, int speed){
this.percentage = percentage;
this.speed = speed;
}
public void proceed(){
percentage+= speed;
}
}
public int[] solution(int[] progresses, int[] speeds) {
int[] answer = new int[progresses.length];
int returnNum = 0;
Queue<Progress> queue = new LinkedList<>();
for(int i = 0; i<progresses.length; i++){
queue.offer(new Progress(progresses[i], speeds[i]));
}
int i = 0;
while(!queue.isEmpty()){
for(Progress p : queue){
returnNum = 0;
while(p.percentage >= 100){
queue.poll(); returnNum++;
}
p.proceed();
if(returnNum != 0){
answer[i] = returnNum;
i++;
}
}
}
return answer;
}
}
초반 코드는 최종 제출한 코드와 로직 자체가 다르다.
처음에는 매번 진행률을 1씩 증가시키는 방향으로 코드를 만들었다. 그런데 이렇게 하니까 시간 초과 ..;^
그래서 방향을 틀어서 진행률이 100% 되기까지 남은 날짜를 먼저 계산해놓는 방식으로 로직을 변경했다.
📌
우선 progresses 배열과 speeds 배열을 Progress 클래스를 통해 queue로 전부 옮긴다.
ㄴ 어제 객체지향 개념을 적극 적용하고자 마음먹었는데 바로 응용해봤다 ㅎ
그리고 큐가 빌때까지 반복문을 돌린다.
그리고 큐를 peek()하여 현재 가장 앞에 위치한 값의 남은 날을 계산하여 변수에 저장해놓는다.
⭐ 그리고 while문을 통하여 큐의 모든 값의 남은 날을 가장 첫 번째 값의 남은 날과 비교한다. 이때, 첫 번째 값의 남은날보다 작거나 같으면 poll하고 completedTasts를 1 증가시킨다.
-> 이렇게 하면 결과적으로 현재 완료된 progrerss들이 함께 큐에서 사라진다.
그리고 answerList에 저장한 값들을 answer 배열로 옮긴다.
+) ArrayList도 생각보다 잘 쓰지 않았는데, 배열로 다루기 까다로울땐 보다 편리하게 사용할 수 있음을 다시 한 번 느꼈다.