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 |
Tags
- 3343
- 호반우 상인
- c++ #입출력 #속도 #ios #sync_with_stdio #cin #cout #tie
- 22869
- 레드아보
- 사이클 없는 그래프
- graph
- 이분탐색 #dp #11053
- 줄어드는수
- C++
- 코딩
- 30870
- graph #최단경로
- hcpc
- backtracking #codetree #디버깅 #삼성코테
- 투포인터 #백준 #boj #20922 #22862
- 백준
- 3D #Reconstruction #computer #vision #volume #metric #tsdf #kinect #fusion
- LIS #가장긴증가하는부분수열 #
- boj #백준
- 1174
- 16202
- c++ #boj #
- 백준 #다익스트라 #dijkstra #9370 #c++
- N번째큰수
- 20117
- BOJ
- 최소 #공배수 #최대 #공약수 #유클리드 #호제법 #lcm #gcd #c++ #boj #3343 #백준 #장미
- 진법변환 #2to10 #10to2 #이진법 #십진법 #변환 #bitset #c++
- 쌤쌤쌤
Archives
- Today
- Total
hyunjin
[level 1]완주하지 못한 선수 2차 풀이, hash, unordered_map 본문
728x90
https://programmers.co.kr/learn/courses/30/lessons/42576
1차 풀이 방법
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
string solution(vector<string> participant, vector<string> completion) {
unordered_map<string, int> hash;
for (string name:completion) {
if (hash.end() == hash.find(name))
hash.insert(make_pair(name, 1));
else
hash[name]++;
}
for (string name : participant) {
if (hash.end() == hash.find(name))
return name;
else {
hash[name]--;
if (hash[name] < 0)
return name;
}
}
}
풀이방법
completion 원소로 <원소 ,개수> pair를 가지는 hash map를 만든다.
그 다음 participant의 원소와 개수를 비교해서 답을 찾는다.
이 때 find를 사용했는데
count(participant.begin(), participant.end(),elem2) != com_map.count(elem2)
이런 식으로 count를 활용해 바로 개수를 통해 답을 구해도 될 듯 하다.
배운 내용
- map이란 인덱스를 문자열로 받는 배열 , unordered_map, map이 있다.
- unorderd_map : hash map으로 구현된다.
- 헤더 파일 : <unordered_map>
- 해당 key가 존재 여부는 find(), count()를 통해
- m.find(elem)
- m.count(elem)
- 삽입 시 m.insert()하고 수정 시 m[key] 방식으로
2차 풀이
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
string solution(vector<string> participant, vector<string> completion) {
sort(participant.begin(),participant.end());
sort(completion.begin(),completion.end());
for(int i = 0 ; i < completion.size() ; i++){
if(completion[i].compare(participant[i]) !=0 ) return participant[i];
}
return participant[participant.size()-1];
}
풀이 방법
hash를 사용하지 않고 sort를 사용한 방법이다.
이름 순으로 정렬한 후 completion과 participant가 달라지는 순간을 찾아 리턴하는 방식이다.
수행시간
O(nlog₂n) : sort알고리즘을 사용해 정렬하는 시간이 보통 O(nlog₂n)이니까
참고 사이트
ordered_map : https://umbum.tistory.com/744
c++의 count, count_id : https://modoocode.com/262
728x90
'알고리즘 연습 > 프로그래머스' 카테고리의 다른 글
[level 1] k 번째 수 , 2차 풀이 (0) | 2020.07.11 |
---|---|
[level 2] 프린터 , queue, max_element=> 활용해 다시 풀어보기 (0) | 2020.07.11 |
[level 1] 문자열 다루기 기본 , isdigit (0) | 2020.07.10 |
[level 2]탑 , 스택/큐 문제 (0) | 2020.07.07 |
[level 1]키패드 누르기 , pair,abs 사용 (0) | 2020.07.06 |