name
: 문자열 배열 (그리워하는 사람 이름)yearning
: 정수 배열 (각 사람의 그리움 점수)photo
: 2차원 문자열 배열 (사진 속 인물들 이름)int[]
: 각 사진별 추억 점수의 합3 ≤ name.length = yearning.length ≤ 100
1 ≤ yearning[i] ≤ 100
3 ≤ photo.length ≤ 100
1 ≤ photo[i].length ≤ 100
name
과 photo[i]
의 원소는 중복 없음class Solution {
public int[] solution(String[] name, int[] yearning, String[][] photo) {
int[] answer = new int[photo.length];
for(int i = 0 ; i < photo.length ; i++ ) {
int sum = 0 ;
for(int j = 0 ; j < photo[i].length ; j++ ) {
for(int n = 0 ; n < name.length ; n++ ) {
// 이름이 존재한다면
if (photo[i][j].equals(name[n])) {
sum += yearning[n] ;
}
}
}
answer[i] = sum ;
}
return answer;
}
}
for (photo[i][j]) {
for (name[n]) {
if (photo[i][j].equals(name[n])) {
sum += yearning[n];
}
}
}
photo
최대 100개name
최대 100명 → O(photo × photo[i] × name) = O(100 × 100 × 100) = 1,000,000 (백만 연산)import java.util.*;
class Solution {
public int[] solution(String[] name, int[] yearning, String[][] photo) {
// 이름 → 그리움 점수 매핑
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];
for (int i = 0; i < photo.length; i++) {
int sum = 0;
for (String person : photo[i]) {
// 이름이 존재하면 점수 더하기
sum += scoreMap.getOrDefault(person, 0);
}
answer[i] = sum;
}
return answer;
}
}
Map
생성: O(name.length) = O(100)이름 → 그리움 점수
매핑을 HashMap에 미리 저장해두고, 조회할 때 O(1)
로 가져오는 방식이 좋을 것 같다.
photo[i][j].equals(name[n])
map.put(x, map.getOrDefault(x, 0) + 1)
패턴 자주 사용값 넣기 : map.put("may", 5);
값 가져오기 : int score = map.get("may");
값 업데이트 : map.put("may", map.getOrDefault("may", 0) + 1);
존재 여부 확인 :
if (map.containsKey("may")) {
System.out.println("있음");
}