조금 오래 걸렸던 문제.. 마지막 테스트케이스만 통과를 못해서 애먹었는데 수연이가 해결에 도움을 주었다. 첫번째와 두번째 모두 마지막 테스트 케이스를 통과하지 못함.
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
class Solution {
public int[] solution(int[] progresses, int[] speeds) {
Queue<Integer> queue = new LinkedList<>();
int[] answer = new int[progresses.length];
int i=0;
for(int k=0; k<progresses.length; k++){
queue.add(k);
}
while(!queue.isEmpty() && i<answer.length){
while(!queue.isEmpty() && progresses[queue.peek()] == 100){ // 순서 중요! nullpointerException
queue.poll();
answer[i]++;
}
if(answer[i] != 0) i++;
for(int j=0; j<progresses.length; j++){
progresses[j] += speeds[j];
if(progresses[j] > 100) progresses[j] = 100;
}
}
int l=0;
while(answer[l] != 0) {
l++;
}
int[] ans = new int[l];
for(int k=0; k<l; k++){
ans[k] = answer[k];
}
return ans;
}
}
```java
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
class Solution {
public int[] solution(int[] progresses, int[] speeds) {
int[] answer = new int[progresses.length];
int[] date = new int[progresses.length];
Queue<Integer> queue = new LinkedList<>();
for(int i=0; i<date.length; i++){ // 완료일수를 계산하여 queue에 add
date[i] = (int)Math.ceil((double)(100-progresses[i]) / (double)speeds[i]);
queue.add(date[i]);
}
if(queue.isEmpty()){
int[] a = new int[1];
a[0] = 0;
return a;
}
int temp = queue.poll();
int i=0;
while(!queue.isEmpty()){
int ans=1;
while(!queue.isEmpty() && temp>=queue.peek()){
queue.poll();
ans++;
}
answer[i++] = ans;
if(!queue.isEmpty()) {
temp = queue.poll();
answer[i] = 1;
}
}
int l=0;
while(answer[l] != 0) {
l++;
}
int[] ans = new int[l];
for(int k=0; k<l; k++){
ans[k] = answer[k];
}
return ans;
//return answer;
}
}
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
class Solution {
public int[] solution(int[] progresses, int[] speeds) {
int indexNum = 0;
int[] answer = new int[progresses.length];
int[] date = new int[progresses.length];
Queue<Integer> queue = new LinkedList<>();
for(int i=0; i<date.length; i++){ // 완료일수를 계산하여 queue에 add
date[i] = (int)Math.ceil((double)(100-progresses[i]) / (double)speeds[i]);
queue.add(date[i]);
}
int i=0;
while(!queue.isEmpty()){
int temp = queue.poll();
int ans=1;
while(!queue.isEmpty()&&temp>=queue.peek()){
queue.poll();
ans++;
}
indexNum++;
answer[i++] = ans;
}
System.out.println("index:"+indexNum);
int[] ans = new int[indexNum];
for(int k=0; k<ans.length; k++){
ans[k] = answer[k];
}
return ans;
}
}
기존 테스트케이스 11번 런타임 에러 문제 이유:
테스트 케이스 [3,2,1],[1,1,1] → [1,1,1]을 해보면 index out of bound에러를 확인할 수 있음.
이유 : 배열길이 수정하는 부분에서 answer[l] != 0 이런식으로 확인하게 되면 l이 answer배열 사이즈를 넘게되는 경우에도 참조되서 에러남.
→ while(l<answer.length) {
if(answer[l] != 0) {
l++;
}
}
이런식으로 수정하게 되면 에러를 잡을 수 있는데 그러면 배열 수정하는 과정에서 기존 배열을 한번 돌면서 길이를 체크하고 또 다른 배열을 선언해서 값을 넣어주는 작업을 하게됨 → 시간초과
해결방안: 인덱스 변수를 선언해서 ans를 계산할때 인덱스를 증가시키고 모든 작업이 끝난후에 인덱스만큼 배열을 선언해주면 위와같은 과정을 할 필요 없음. 코드도 간결!
에러 해결!