새소식

코딩테스트/프로그래머스

[C++] 완주하지 못한 선수

  • -

[문제]

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


[문제 풀이]

participant 벡터에서 완주한 선수를 제외하고 남은 선수를 return하는 문제이다.

c++ map이나 set과 같은 key - value 값을 쓰는 자료구조를 알고 있다면 풀기가 어렵지 않았을 것이다.

또한, 문제에서 1명만 완주를 못했다고 설명을 해줬으니 앞에서 중복되는 값이 아닌값이 나오자마자 return을 해주면 된다.


[코드]

#include <string> #include <vector> #include <map> using namespace std; string solution(vector<string> participant, vector<string> completion) { string answer = ""; map<string, int> total;//key - value를 알기 위해서 map 사용 for(int i = 0;i<participant.size();i++){ //participant 반복 => O(n) total[participant[i]]++; // participant 이름들 체크 } for(int i = 0;i<completion.size();i++){ // completion 반복 => O(n) total[completion[i]]--; //중복된 값은 value 값 0으로 초기화 } auto iter = total.begin(); //iter를 통해서 map 모두 반복할 예정 while(iter != total.end()){ //iter가 마지막이 되기 전까지 반복 if(iter->second == 1){ //만일 completion에서 중복되지 않은 값이 나온다면 answer = iter->first; //answer는 해당 key값으로 바꾸고 break; // 종료 } iter++; } return answer; }
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.