(Java)프로그래머스 - 추억 점수

윤준혁·2024년 2월 25일

나의 풀이

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++) { // 1
            for (int j = 0; j < photo[i].length; j++) { // 2
                for (int k = 0; k < name.length; k++) { // 3
                    if (photo[i][j].equals(name[k])) { // 4
                        answer[i] += yearning[k]; // 5
                    }
                }
            }
        }
        
        return answer;
    }
}

과정

  1. photo 배열의 행 탐색(사진을 의미)
  2. photo 배열의 열 탐색(사진 안에 담겨있는 사람을 의미)
  3. name 배열의 길이 탐색(그리워 하는 사람의 배열)
  4. photo 배열의 i행 j열이 name의 k번째와 같다면(사진 i에 사람 k가 있다면)
  5. answer 배열의 i번째에 yearning 배열의 k번째를 더해준다

다른 사람 풀이

import java.util.*;
import java.util.stream.*;

class Solution {
    public int[] solution(String[] name, int[] yearning, String[][] photo) {
        Map<String, Integer> map = IntStream.range(0, name.length).mapToObj(operand -> Map.entry(name[operand], yearning[operand])).collect(Collectors.toSet()).stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        return Arrays.stream(photo).mapToInt(strings -> Arrays.stream(strings).mapToInt(value -> map.getOrDefault(value, 0)).sum()).toArray();
    }
}
  • 가독성은 떨어지지만 배열의 크기에 따라서는 더 높은 성능을 보여줄 수 있을 것 같다

0개의 댓글