Algorithm/java
[Java][프로그래머스] 기능개발
현이승
2023. 5. 3. 16:51
처음
int index = 0;
int target = queue.poll();
list.add(1);
while(queue.size() >= 1){
int next = queue.peek();
if(target >= next){
list.set(index, list.get(index)+1);
queue.remove();
}
else{
index += 1;
list.add(index, 1);
target = next;
queue.remove();
}
}
처음 코드를 짤 때 큐에 모든 작업을 추가한 뒤
위와 같이 poll()과 peek()를 사용하여 처음과 다음을 비교하면서 진행했었는데
이렇게 하면 같이 배포 될 수 있는 작업을 구하기 위해 불필요한 변수와 연산이 생겨났다.
자바 코드
import java.util.*;
class Solution {
public int[] solution(int[] progresses, int[] speeds) {
Queue<Integer> queue = new LinkedList<>();
ArrayList<Integer> list = new ArrayList<>();
for(int i=0; i<progresses.length; i++){
double re = (100-progresses[i])/(double) speeds[i];
int day = (int) Math.ceil(re);
if(!queue.isEmpty() && queue.peek() < day){
list.add(queue.size());
queue.clear();
}
queue.add(day);
}
list.add(queue.size());
int[] answer = new int[list.size()];
for(int i=0; i<list.size(); i++){
answer[i] = list.get(i);
}
return answer;
}
}
ArrayList를 사용하는 이유는 크기가 정해져 있지 않기 때문이고 이를 다시 int 배열로 바꿔준다.
Math.ceil() 함수를 통해 올림을 하여 해당하는 날짜를 계산한다.
큐의 헤드 값이 해당 날짜보다 작다면 같이 배포될 수 없으므로 list에 값을 추가하고 큐를 비워준다.
이후 큐에 해당 날짜를 다시 더한다.
핵심은 list에 큐의 사이즈만큼 더해줌으로써 같이 배포될 수 있는 작업을 계산하는 것이다.