Home [프로그래머스] 완주하지 못한 선수
Post
Cancel

[프로그래머스] 완주하지 못한 선수

[프로그래머스] 완주하지 못한 선수

https://programmers.co.kr/learn/courses/30/lessons/42576

풀이방법

  • HashMap을 이용해 풀이
  • 동일 이름이 있을 수 있다고 했으므로 참가자의 값들이 이미 HashMap에 있을 경우에는 value를 가져와 +1
  • 완주자의 경우 HashMap에 해당 키값을 찾아 -1
  • 결국 0이 되지 않는 키값이 미완주자이므로 출력
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.HashMap;
import java.util.Map;

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

        for (String p : participant) {
            hmParticipant.put(p, (int)hmParticipant.getOrDefault(p, 0) + 1);
        }

        for (String c : completion) {
            hmParticipant.put(c, (int)hmParticipant.getOrDefault(c, 0) - 1);
        }

        for(Map.Entry<String, Integer> entry : hmParticipant.entrySet()) {
            if (entry.getValue() > 0) {
                answer = entry.getKey();
                break;
            }
        }

        return answer;
    }
}
This post is licensed under CC BY 4.0 by the author.

LiveData

[프로그래머스] 전화번호 목록

Comments powered by Disqus.