2026.03.04
소요 시간: 10분 24초
정답률 71%의 아주 쉬운 난이도의 문제라 그런지 푸는 데에 하나도 막힘이 없었음.
나의 정답
class Solution { public int[] solution(String[] name, int[] yearning, String[][] photo) { int[] answer = {}; answer = new int[photo.length]; for (int i = 0; i < answer.length; i++) { answer[i] = 0; } for (int i = 0; i < photo.length; i++) { for (int j = 0; j < photo[i].length; j++) { String person = photo[i][j]; for (int n = 0; n < name.length; n++) { if (person.equals(name[n])) { answer[i] += yearning[n]; } } } } return answer; } }
AI 정답
HashMap의
getOrDefault()활용
scoreMap에서person을 탐색함- 이름이 있다면 그 사람의 점수를 반환함
- 이름이 없다면 미리 설정한 기본값인
0을 반환함import java.util.*; class Solution { public int[] solution(String[] name, int[] yearning, String[][] photo) { // 1. 이름과 점수를 매칭하여 Map에 저장 (조회 속도 최적화) Map<String, Integer> scoreMap = new HashMap<>(); for (int i = 0; i < name.length; i++) { scoreMap.put(name[i], yearning[i]); } int[] answer = new int[photo.length]; // 2. 사진첩을 돌면서 점수 합산 for (int i = 0; i < photo.length; i++) { int currentSum = 0; for (String person : photo[i]) { // Map에 이름이 존재하면 점수를 더하고, 없으면 0을 더함 currentSum += scoreMap.getOrDefault(person, 0); } answer[i] = currentSum; } return answer; } }