-
카테고리
-
세부 분야
알고리즘 · 자료구조
-
해결 여부
미해결
list로 풀었는데 런타임오류가 납니다
22.10.11 16:04 작성 조회수 282
0
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int K = sc.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = sc.nextInt();
}
new Main().solution(N, K, arr);
}
private void solution(int N, int K, int[] arr) {
int lt = 0;
int cnt = 0;
List<Integer> list = new ArrayList<>();
for (int rt = 0; rt < N; rt++) {
if (list.contains(arr[rt])) {
cnt++;
}
list.add(arr[rt]);
if (rt - lt + 1 == K) {
System.out.print((K - cnt) + " ");
list.remove(lt++);
cnt = 0;
}
}
}
}
안녕하세요 위와 같이 list로 풀어봤는데
ide에서 답은 제대로 나옵니다
근데 채점사이트에서는 런타임 오류가 발생하는데 왜 안되는지 궁금합니다
답변을 작성해보세요.
1
oort_cloud98
2022.10.11
반례입니다.
N = 5, K = 2
20 12 20 12 10
답 : 2 2 2 2
출력 : 인덱스 에러if (rt - lt + 1 == K) {
System.out.print((K - cnt) + " ");
list.remove(lt++);
cnt = 0;
}
해당 구문에서 index 에러가 나오는 경우가 있습니다.
list에서 remove() 메서드 사용시 list의 size는 줄어들고 list속 데이터는 한칸씩 앞으로 줄어듭니다.
size가 3인 list
{1, 2, 3} 이 존재 할 때
list.remove(1) -- list[1] 삭제
{1, 3} size -> 2로 변경
list[1] = 3
list[2] --- index error
답변 1