문제는 프로그래머스에서 확인 할 수 있다.
모든 경우를 판단, 완전 탐색
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
using namespace std;
/* sort에서 사용할 비교 함수 */
bool cmp(const pair<int,int> &a, const pair<int, int> &b){
if (a.second == b.second ) return a.first<b.first;
return a.second > b.second;
}
vector<int> solution(vector<int> answers) {
vector<int> answer;
vector<int> std1 = {1,2,3,4,5};
vector<int> std2 = {2,1,2,3,2,4,2,5};
vector<int> std3 = {3,3,1,1,2,2,4,4,5,5};
map<int, int> score;
int max = 0;
for( int i=0; i<answers.size(); i++ ){
/* std의 원소 갯수를 생각해서 % 연산 */
if(answers[i] == std1[i%5]){score[1]++;}
if(answers[i] == std2[i%8]){score[2]++;}
if(answers[i] == std3[i%10]){score[3]++;}
}
/* 모두의 답이 틀린경우 segmetaion falut 발생. 이를 방지 */
if( score.empty() != true ){
/* map을 vector로 변환, value를 이용한 정렬 */
vector<pair<int, int>> v( score.begin(), score.end() );
sort(v.begin(), v.end(), cmp);
max = v.begin()->second;
for( int i=0; i<v.size(); i++){
if( max == v[i].second ){
answer.push_back(v[i].first);
}
}
}
return answer;
}
int main(void){
vector<int> answers = {1,2,3,4,5};
vector<int> ret;
ret = solution(answers);
for( auto elem : ret ){
cout << elem << endl;
}
return 0;
}
vector<pair<int, int>> v (score.begin(), score.end());
문제를 해결하고 다른 사람들의 풀이를 보니, 나는 최대값을 가진 value를 구하기위해 sort() 하는 방식 외에도 max_element() 함수를 사용하여 최대값을 가진 value를 구하는 방식도 존재했다.
이를 참고하여 다시 코드를 작성하였다.
모든 경우를 판단, 완전 탐색
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> answers) {
vector<int> answer;
vector<int> std1 = {1,2,3,4,5};
vector<int> std2 = {2,1,2,3,2,4,2,5};
vector<int> std3 = {3,3,1,1,2,2,4,4,5,5};
vector<int> score(3);
int max = 0;
for( int i=0; i<answers.size(); i++ ){
/* std의 원소 갯수를 생각해서 % 연산 */
if(answers[i] == std1[i%5]){score[0]++;}
if(answers[i] == std2[i%8]){score[1]++;}
if(answers[i] == std3[i%10]){score[2]++;}
}
if( score.empty() != true ){
/* score 벡터에서 가장 높은 점수를 취득 */
max = *max_element(score.begin(), score.end());
/* 가장 높은 점수를 가진 사람 확인 */
for ( int i=0; i<score.size(); i++ ){
if( max == score[i] ){
answer.push_back(i+1);
}
}
}
return answer;
}
int main(void){
vector<int> answers = {1,3,2,4,2};
vector<int> ret;
ret = solution(answers);
for( auto elem : ret ){
cout << elem << endl;
}
return 0;
}