< 문제링크 >
https://www.welcomekakao.com/learn/courses/30/lessons/42840
< 풀이 >
1. 1번, 2번, 3번 수포자가 맞춘 문제수를 계산
2. 제일많이 맞춘 개수를 찾아냄
3. 그 찾아낸 점수에 해당하는 사람을 오름차순으로 저장
< 내가 푼 방법 >
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> one = { 1,2,3,4,5 };
vector<int> two = { 2,1,2,3,2,4,2,5 };
vector<int> three = { 3,3,1,1,2,2,4,4,5,5 };
// 맞춘 수에 대해서는 내림차순, 사람의 인덱스에 대해서는 오름차순
bool cmp(pair<int, int> a, pair<int, int> b)
{
if (a.second > b.second) return true;
else if (a.second == b.second) {
return a.first < b.first;
}
return false;
}
// 해당 사람이 맞춘 문제 개수를 return
int solve(vector<int> arr, vector<int> answers)
{
int correct = 0;
for (int i = 0; i < answers.size(); i++) {
if (answers[i] == arr[i%arr.size()]) correct++;
}
return correct;
}
vector<int> solution(vector<int> answers) {
vector<int> answer;
vector<pair<int, int>> correct;
// (사람, 맞춘개수) 쌍으로 저장
correct.push_back({ 1, solve(one, answers) });
correct.push_back({ 2, solve(two, answers) });
correct.push_back({ 3, solve(three, answers) });
// 점수에 대해서 내림차순, 같으면 사람번호에 대해서 오름차순 정렬
sort(correct.begin(), correct.end(), cmp);
// 처음요소가 최대점수
answer.push_back(correct[0].first);
int value = correct[0].second;
// 두번째 요소가 최대점수인가 확인
if (value == correct[1].second) {
answer.push_back(correct[1].first);
}
// 세번째 요소가 최대점수인가 확인
if (value == correct[2].second) {
answer.push_back(correct[2].first);
}
return answer;
}
< 더 나은 코드 - max_element() 함수 사용 >
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> one = { 1,2,3,4,5 };
vector<int> two = { 2,1,2,3,2,4,2,5 };
vector<int> three = { 3,3,1,1,2,2,4,4,5,5 };
vector<int> solution(vector<int> answers) {
vector<int> answer;
vector<int> correct(3);
// 정답 개수를 correct 벡터에 누적
for (int i = 0; i < answers.size(); i++) {
if (one[i%one.size()] == answers[i]) correct[0]++;
if (two[i%two.size()] == answers[i]) correct[1]++;
if (three[i%three.size()] == answers[i]) correct[2]++;
}
// max_element() : 정해준 구간안에서 최대값을 가지는 값의 주소를 return
int cor_max = *max_element(correct.begin(), correct.end());
// 최대값과 같은 정답수를 맞춘 사람들을 answer에 추가
for (int i = 0; i < 3; i++) {
if (cor_max == correct[i]) answer.push_back(i+1);
}
return answer;
}
'알고리즘 > Programmers' 카테고리의 다른 글
Programmers / 완전탐색 / 카펫 (0) | 2020.09.09 |
---|---|
Programmers / 완전탐색 / 소수 판별 (0) | 2020.09.08 |
Programmers / Sort / H-index (0) | 2020.09.07 |
Programmers / Sort / 가장 큰 수 (0) | 2020.09.07 |
Programmers / Sort / K번째수 (0) | 2020.09.06 |