반응형
76. 추억 점수

문제

import java.util.*;

class Solution {
    public int[] solution(String[] name, int[] yearning, String[][] photo) {
        int[] answer = new int[photo.length];
        Map<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++){
            String[] persons = photo[i];
            int score = 0;
            
            for(int j=0; j<persons.length; j++){
                String person = persons[j];
                if(map.containsKey(person)){
                    score += map.get(person);
                }
            }
            answer[i] = score;
        }
        
        return answer;
    }
}

<작성한 코드>

answer의 길이는 photo 배열 길이만큼 지정했다. Map구조의 변수 map을 만들어서 값을 입력해 줬다. 첫 번째 for문에서 String값인 각 name을 key값, 각 yearning을 value로 지정해 줬다. 두 번째 for문에서는 photo의 길이만큼 반복문을 실행했고 photo의 각 배열마다 persons로 묶어줬다. 그 뒤 점수를 계산할 변수 score를 만들어준 뒤 다시 한번 for문을 사용했다. j번째 person값을 변수에 저장하고 map에 그 person을 key값으로 갖는 값이 있는지 찾아서 존재한다면 score에 더해줬다. 그 뒤 answer [i]에 score값을 저장해 줬다. 마지막으로 answer을 반환했다.

 

 

 

77. 달리기 경주

문제

import java.util.*;

class Solution {
    public String[] solution(String[] players, String[] callings) { 
        Map<String, Integer> map = new HashMap<>();
        for(int i=0; i<players.length; i++){
            map.put(players[i], i);
        }
        
        for(String player : callings){
            int rank = map.get(player);
            String beforePlayer = players[rank-1];
            
            players[rank-1] = player;
            players[rank] = beforePlayer;
            
            map.put(player, rank-1);
            map.put(beforePlayer, rank);
        }
        
        return players;
    }
}

<작성한 코드>

Map형식의 변수 map을 생성해줬다. 그 뒤 players에 있는 값들을 key값으로 선언하고 벨류는 0부터 순위를 갖게 하였다. 그 뒤 callings에서 불린 선수들을 기준으로 반복문을 돌렸다. int형 변수 rank에는 이름이 불린 선수의 순위를 저장시켰고, beforePlayer에는 해당 순위의 앞선수를 저장시켰다. 그 뒤 두 명의 선수의 값을 players에서 한번 바꿔주고 map에서 한번 더 바꿔줬다. 그 뒤 players를 반환하였다.

반응형

+ Recent posts