본문 바로가기
IT/알고리즘

[프로그래머스 코테연습] 해시 1. 완주하지 못한 선수

by 뷰IGHT 2021. 4. 15.

비교하고 배운점

1. HashMap에는 getOrDefault(key, defaultValue) 라는 함수가 있다. 
   : 찾는 키가 존재하면 해당 키의 값을 반환, 존재하지 않으면 2번째 인자로 넣은 default 값을 반환

2. Iterator를 굳이 쓰지 않아도 foreach 문에 콜렉션 넣는 부분에 hashmap.keySet() 넣으면 된다. 

 

내 풀이

import java.util.*;

class Solution {
    public String solution(String[] participant, String[] completion) {
        HashMap<String, Integer> hashParticipant = new HashMap<String, Integer>();
        HashMap<String, Integer> hashCompletion = new HashMap<String, Integer>();

        List<String> list = new ArrayList<String>();
        for (int i = 0; i< participant.length; i++) {

            if (hashParticipant.containsKey(participant[i])) {
                hashParticipant.put(participant[i], hashParticipant.get(participant[i]) + 1);   
            } else {
                hashParticipant.put(participant[i], 1);
            }
        }
        
        for (int i = 0; i< completion.length; i++) {
            if (hashParticipant.containsKey(completion[i])) {
                hashParticipant.put(completion[i], hashParticipant.get(completion[i]) - 1);
            }
        }

        Iterator<String> keys = hashParticipant.keySet().iterator();
        String remainOne = "";
        while (keys.hasNext()) {
            String key = keys.next();
            if (hashParticipant.get(key) > 0) {
                remainOne = key;
                break;
            }
        }

        return remainOne;
    }
}

 

정답풀이

import java.util.HashMap;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        HashMap<String, Integer> hm = new HashMap<>();
        for (String player : participant) hm.put(player, hm.getOrDefault(player, 0) + 1);
        for (String player : completion) hm.put(player, hm.get(player) - 1);

        for (String key : hm.keySet()) {
            if (hm.get(key) != 0){
                answer = key;
            }
        }
        return answer;
    }
}