본 문제는 hashmap 을 활용하여 해결해야 되는 문제입니다.

요구사항

  • n개의 참가자
  • n-1개의 완료자
  • 완주하지 못한 선수를 찾자.
  • 다만, 이름이 중복되는 경우도 있음.

유의사항

  • HashMap 은 하나만 사용해야 됨. 두 개를 사용할 경우 메모리 초과 에러 발생
  • 이름이 중복되는 경우에도 처리 가능해야 됨

Source Code

import java.util.*;

class Main {

    static public String solution(String[] participant, String[] completion) {
        String answer = "";
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (int i = 0; i < participant.length; i++) {
            if (map.get(participant[i]) == null) {
                map.put(participant[i], 1);
            } else {
                map.put(participant[i], map.get(participant[i])+1);
            }
        }
        for (int i = 0; i < completion.length; i++) {
            map.put(completion[i], map.get(completion[i])-1);
        }
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (entry.getValue() > 0) return entry.getKey();
        }
        return answer;
    }

    public static void main(String[] args) throws IOException {
        String participants[] = {"mislav", "stanko", "mislav", "ana"};
        String completion[] = {"stanko", "ana", "mislav"};

        String answer = solution(participants, completion);
        System.out.println(answer);
    }

}

+ Recent posts