Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- dfs
- 스택
- 후니의 쉽게 쓴 시스코 네트워킹
- 위상정렬
- 문자열
- 백트래킹
- BFS
- 세그먼트 트리
- JUnit 5
- 유니온 파인드
- Effective Java
- 완전탐색
- 백준
- CS
- 구현
- 이분탐색
- 에라토스테네스의 체
- 플로이드-와샬
- 동적계획법
- Kotlin
- mst
- 그리디
- 수학
- Network
- swea
- 알고리즘
- 프로그래머스
- 투 포인터
- 시뮬레이션
- java
Archives
반갑습니다!
[프로그래머스] 완주하지 못한 선수 본문
풀이
참여 선수 배열의 크기가 완주 선수 배열의 크기보다 항상 1만큼 크다. 따라서 이를 이용해서 해결하면 된다. 아래의 코드는 참여 선수의 이름을 Key로, 참여 선수 이름의 갯수를 Value로 하는 맵을 통해 해결했다. 참여 선수 배열을 순회하며 맵에 저장하고, 완주 선수 배열을 순회하며 맵의 Value를 1씩 감소시킨다. 이 때 Value가 0이 되는 경우 맵에서 삭제시킨다. 이렇게하면 모든 배열을 순회했을 때 맵에 남아있는 Key 값이 완주하지 못한 선수가 된다.
코드
C++
#include <string>
#include <vector>
#include <map>
using namespace std;
string solution(vector<string> participant, vector<string> completion) {
string answer = "";
map<string, int> m;
for (string name : participant) m[name]++;
for (string name : completion)
if (m[name] > 1) m[name]--;
else m.erase(name);
for (auto it : m) {
answer = it.first;
break;
}
return answer;
}
Java
import java.util.HashMap;
class Solution {
public String solution(String[] participant, String[] completion) {
String answer = "";
HashMap<String, Integer> map = new HashMap<>();
for (String name : participant)
map.put(name, map.getOrDefault(name, 0) + 1);
for (String name : completion) {
if (map.get(name) > 1) map.put(name, map.get(name) - 1);
else map.remove(name);
}
answer = map.keySet().iterator().next();
return answer;
}
}
'알고리즘 문제 풀이' 카테고리의 다른 글
[프로그래머스] 베스트앨범 (0) | 2020.09.06 |
---|---|
[프로그래머스] 위장 (0) | 2020.09.06 |
[백준] 4485 녹색 옷 입은 애가 젤다지? (0) | 2020.09.05 |
[프로그래머스] 기지국 설치 (0) | 2020.09.05 |
[프로그래머스] 배달 (0) | 2020.09.05 |