프로그래머스 추억점수

정상민·2023년 7월 13일

문제 링크

풀이 1

3중 포문으로 해버리기
  1. photo을 돌면서
  2. photo[i]안에 이름들이
  3. name배열 안에 있는지확인
  4. 있으면 더하기
  5. photo[i] 다돌았으면 answer[i]에 합한 값 넣기
  6. photo[i+1]로 반복
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++){
                String now = photo[i][j];
                for(int k=0;k<name.length;k++){
                    if(name[k].equals(now)){
                        sum += yearning[k];
                        break;
                    }
                }
            }
            answer[i] = sum;
        }
        return answer;
    }
}

이렇게 무작정 반복문으로도 가능

채점결과

풀이 2

name,yearning배열을 map 자료구조로 변환
  1. name.length 만큼 반복문 돌면서 map에 key-name, value-yearning 으로 저장
  2. photo를 돌면서
  3. photo[i] 를 돈다
  4. photo[i][j] 값이 map에 있으면 더하고 아님 말고
  5. 더한 값을 answer[i]에 저장
  6. photo[i+1]로 반복

이렇게 하면 3중 for문을 2중 for문으로 바꾸기 가능

import java.util.*;
class Solution {
    public int[] solution(String[] name, int[] yearning, String[][] photo) {
        int[] answer = new int[photo.length];
        HashMap<String,Integer> map = new HashMap<>();
        for(int i=0;i<name.length;i++){
            map.put(name[i],yearning[i]);
        }
        for(int i=0;i<photo.length;i++){
            int sum = 0;
            for(int j=0;j<photo[i].length;j++){
                String now = photo[i][j];
                if(map.get(now) != null){
                    sum += map.get(now);
                }
            }
            answer[i] = sum;
        }
        return answer;
    }
}

채점결과

후기

  • 두번째 풀이로 했을 때 시간이 줄어든 모습 확인
  • 코딩테스트였다면 입력값 범위 확인 후 풀이1로 했을 듯
  • Hashmap 등등 자료구조를 적극 활용하자
profile
안녕하세요! 개인 공부를 꾸준히 기록하는 공간입니다.

1개의 댓글

comment-user-thumbnail
2023년 7월 13일

오옹....

답글 달기