[JAVA] 완주하지 못한 선수

dada·2024년 9월 16일
0

algorithm

목록 보기
7/17

HASH 안 쓰고 푸는 방법

import java.util.Arrays;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        
        Arrays.sort(participant);
        Arrays.sort(completion);
        
        for(int i = 0 ; i<completion.length; i++){
            if(!participant[i].equals(completion[i])){
                return participant[i];
            }
        }
        return participant[participant.length-1];
    }
}

HASH 사용한 풀이

import java.util.HashMap;
import java.util.Map;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        Map<String, Integer> map = new HashMap<>();

        for (String s : participant) {
            // key인 s가 없는 경우 1, 있는 경우 +1
            map.put(s, map.getOrDefault(s, 0) + 1);
        }

        for (String s : completion) {
            // 완주한 경우 map에서 키에 해당하는 value를 1 뺌
            map.put(s, map.get(s) - 1);
        }

        for (String s : map.keySet()) {
            // 완주하지 못한 경우 값이 1보다 큰 값을 가지게 됨
            if (map.get(s) > 0) {
                answer = s;
                break;
            }
        }

        return answer;
    }
}
  • getorDefaults(a, b): 찾는 키 a가 존재할 경우 a에 해당하는 value를 반환하고, 만약 없다면 b값을 반환하는 함수
profile
CV, Vision AI 등을 공부합니다

0개의 댓글