• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

매출액의 종류 문제 질문있습니다.

23.10.30 00:50 작성 조회수 146

0

해당 문제를 다음과 같이 풀었는데 RunTime Error가
발생하는 이유가 뭘까요 ?
혹시 시간초과가 되는것일까요 ?


import java.util.HashMap;
import java.util.Scanner;

public class No3 {
    public static void solution(int n, int m, int[] arr) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] answer = new int[m];

        int lt = 0;
        for (int i = 0; i < m; i++) {
            map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
        }

        answer[0] = map.size();

        for (int rt = m; rt < n; rt++) {
            map.put(arr[lt], map.getOrDefault(arr[lt], 0) - 1);
            map.put(arr[rt], map.getOrDefault(arr[rt], 0) + 1);
            if (map.get(arr[lt]) == 0)
                map.remove(arr[lt]);
            answer[++lt] = map.size();
        }

        for (int x : answer)
            System.out.print(x + " ");
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[] arr = new int[n];

        for (int i = 0; i < n; i++)
            arr[i] = sc.nextInt();

        solution(n, m, arr);
    }
}

답변 2

·

답변을 작성해보세요.

1

sehunkim님의 프로필

sehunkim

2023.10.30

시간초과는 시간초과라고 따로 출력이 나오는 것으로 알고 있습니다.

해당 코드에서 런타임 에러가 나올 경우에 생각할 수 있는 것은 OutOfBound 관련입니다. 즉 배열 인덱스가 배열의 크기보다 커져 잘못된 접근을 수행하는 것으로 보입니다.

0

안녕하세요^^

answer의 크기가 작아서 그런 것 같습니다.

 int[] answer = new int[n];

위와 같이 잡으면 컴파일 에러는 해결될 겁니다.