강의

멘토링

커뮤니티

Inflearn Community Q&A

ddd4148513400's profile image
ddd4148513400

asked

Coding Test Practice Test (with C++): For Large Companies

3. Battle game code description (hash, efficiency)

자바런타임에러

Written on

·

452

0

자바로 로직을 작성했는데 런타임에러가 뜹니다. 테케를 알 수 없어서 방황중인데 무엇이 문제인가요..?

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) throws IOException {

        int n = Integer.parseInt(br.readLine());
        int result[] = new int[n];
        ArrayList<User> list = new ArrayList<>();
        for(int i=0; i<n; i++){
            String[] s = br.readLine().split(" ");
            list.add(new User(s[0].charAt(0), Integer.parseInt(s[1]), i));
        }

        Collections.sort(list);
        HashMap<Character, Integer> hm = new HashMap<>();
        int i=1, j=0;
        int sum = 0;
        while (i<n && j<=i){
            User user_i = list.get(i);
            User user_j = list.get(j);

            if(user_i.val <= user_j.val){
               result[user_i.index] = sum-hm.getOrDefault(user_i.alpa, 0);
                i++;
            }else{
                hm.put(user_j.alpa, hm.getOrDefault(user_j.alpa, 0) + user_j.val);
                sum+=user_j.val;
                j++;
            }
        }
        for(i=0; i<n; i++){
            System.out.println(result[i]);
        }
    }
    static class User implements Comparable<User>{
        char alpa;
        int val;
        int index;
        public User(char a, int b, int c){
            alpa=a; val=b; index=c;
        }

        @Override
        public int compareTo(User o) {
            if(val-o.val > 0) { return 1;}
            return -1;
        }
    }
}

 

Answer 1

0

codingcamp님의 프로필 이미지
codingcamp
Instructor

안녕하세요^^

런타임 에러가 나는 케이스가 모두 n크기가 10만개 이상입니다. n크가 큰 케이스에서 문제가 발생하는 것 같습니다.

compareTo 메서드를 바꾸니 런타임에러는 나지 않습니다.

static class User implements Comparable<User>{
        char alpa;
        int val;
        int index;
        public User(char a, int b, int c){
            alpa=a; val=b; index=c;
        }
        @Override
	public int compareTo(User ob){
		return this.val - ob.val;
	}
    }

 

 

ddd4148513400's profile image
ddd4148513400

asked

Ask a question