티스토리 뷰
https://programmers.co.kr/learn/courses/30/lessons/42576
코딩테스트 연습 - 완주하지 못한 선수
수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다. 마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수��
programmers.co.kr
[풀이 과정]
1. 참가자의 이름이 동일할 수 있기 때문에 Map을 활용하여 몇 명인지 확인한다.
2. 참가자의 이름을 key로, 해당 이름을 가진 선수의 수를 value로 설정한다.
3. 참가장 한 명당 value를 1씩 증가시킨다.
4. 완주자 한 명당 value를 1씩 감소시킨다.
5. 완주자가 아닌(value가 0이 아닌) 사람을 구한다.
※ 자바 최신 문법을 지원해서 자바 8으로도 풀어봤다.
[소스 코드]
import java.util.HashMap;
import java.util.Map;
public class CannotCompletePlayer {
private static final int FINAL_POSITION = 0;
public static void main(String[] args) {
String[] participant = {"leo", "kiki", "eden"};
String[] completion = {"eden", "kiki"};
System.out.println(solution(participant, completion));
System.out.println(solution1(participant, completion));
}
// 풀이 1
private static String solution(String[] participant, String[] completion) {
String answer = "";
Map<String, Integer> maps = new HashMap<>();
for (String player : participant) {
maps.put(player, 0);
}
for (String player : participant) {
maps.put(player, maps.get(player) + 1);
}
for (String player : completion) {
maps.put(player, maps.get(player) - 1);
}
for (Map.Entry<String, Integer> entry : maps.entrySet()) {
if (entry.getValue() != 0) {
answer = entry.getKey();
break;
}
}
return answer;
}
// 풀이2
private static String solution1(String[] participant, String[] completion) {
Map<String, Integer> maps = new HashMap<>();
for (String player : participant) {
maps.put(player, maps.getOrDefault(player, 0) + 1);
}
for (String player : completion) {
maps.put(player, maps.get(player) - 1);
}
return maps.entrySet().stream()
.filter((map) -> isNotComplete(map.getValue()))
.map(Map.Entry::getKey)
.findFirst()
.orElseThrow(NotFoundInCompletePlayer::new);
}
private static boolean isNotComplete(Integer value) {
return value != FINAL_POSITION;
}
static class NotFoundInCompletePlayer extends RuntimeException {
private static final String MESSAGE = "완주자를 찾을 수 없습니다.";
public NotFoundInCompletePlayer() {
super(MESSAGE);
}
}
}
'알고리즘 문제풀이 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 2016년 (lv.1) (0) | 2020.06.25 |
---|---|
[프로그래머스] 체육복 (lv.1) (0) | 2020.06.24 |
[프로그래머스] K번째수 (lv.1) (0) | 2020.06.24 |
[프로그래머스] 모의고사 (lv.1) (0) | 2020.06.23 |
[프로그래머스] 크레인 인형뽑기 게임 (lv.1) (0) | 2020.06.22 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- DP
- BOJ
- 열혈강의
- 코틀린
- programmers
- 2020 카카오 인턴십
- 깃
- 구현
- 저장소
- 알고리즘
- spring boot 2.3.1
- 2019 카카오 개발자 겨울 인턴십
- 정렬
- OS
- 그리디
- repository
- git
- bfs
- Algorithm
- dfs
- 자료구조
- 백준
- Algorihtm
- 단계별로 문제풀이
- 그래프
- binary search
- Python
- 이것이 코딩테스트다
- Summer/Winter Coding(~2018)
- Idempotent
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 27 | 28 | 29 | 30 | 31 |
글 보관함