Skip to main content

[Java] 176963 추억 점수


1. 문제

추억 점수

2. 접근방법

  1. HashMap<String, Integer>로 name, yearning을 매핑한다.
  2. photo를 순회하면서 key값인 name으로 value를 불러와 answer[i]에 저장한다.

3. 오답코드

import java.util.*;

class Solution {
    public int[] solution(String[] name, int[] yearning, String[][] photo) {
        int[] answer = new int[photo.length];
        HashMap<String, Integer> scoreMap = new HashMap<>();
        
        for (int i = 0; i < name.length; i++) {
            scoreMap.put(name[i], yearning[i]);
        }
        
        for (int i = 0; i < photo.length; i++) {
            for (int j = 0; j < photo[i].length; j++) {
                answer[i] += scoreMap.get(photo[i][j]);
            }
        }
        
        return answer;
        
    }
}
  1. answer 배열 크기
    • 처음에 answer 배열을 name.length로 초기화함 → photo.length 로 수정
  2. getOrDefault
    • scoreMap.get(photo[i][j]) 쓸 때 만약 해당 이름이 없으면 NullPointerException이 난다
    • 문제에서 그리움 점수가 없는 사람도 있다고 했기 때문에 getOrDefault 처리를 꼭 해야 한다.

image.png


4. 정답코드

import java.util.*;

class Solution {
    public int[] solution(String[] name, int[] yearning, String[][] photo) {
        int[] answer = new int[photo.length];
        HashMap<String, Integer> scoreMap = new HashMap<>();
        
        for (int i = 0; i < name.length; i++) {
            scoreMap.put(name[i], yearning[i]);
        }
        
        for (int i = 0; i < photo.length; i++) {
            for (int j = 0; j < photo[i].length; j++) {
                answer[i] += scoreMap.getOrDefault(photo[i][j], 0);
            }
        }
        
        return answer;
    }
}