- 문제 풀이
"완전 탐색"을 사용하는 문제였다.
for문을 통해 점수를 하나씩 탐색하며 맞혔다면 count해주어야 했다.
- 코드
+ 나는 1차원벡터를 3개 만들어 각 학생의 답을 저장했는데, vector<vector<int>> s_answer { {1,2,3,4,5}, {2,1,...}, {3,3,...}}; 2차원 벡터의 형태로 저장하는 게 더 깔끔한 것 같다.
+ 나는 맞힌 문제 개수가 들어있는 벡터에서 최댓값을 찾을 때 for문으로 탐색하는 방법을 사용했는데, *max_element()함수를 통해 간단하게 구할 수 있다.
제출한 코드는 다음과 같다.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> answers) {
vector<int> answer;
vector<int> temp;
vector<int> s1;
vector<int> s2;
vector<int> s3;
//학생이 제출한 답이 들어있는 벡터 생성
for(int i=0; i<5; i++)
s1.push_back(i+1);
s2.push_back(2);
s2.push_back(1);
s2.push_back(2);
s2.push_back(3);
s2.push_back(2);
s2.push_back(4);
s2.push_back(2);
s2.push_back(5);
s3.push_back(3);
s3.push_back(3);
s3.push_back(1);
s3.push_back(1);
s3.push_back(2);
s3.push_back(2);
s3.push_back(4);
s3.push_back(4);
s3.push_back(5);
s3.push_back(5);
//학생별로 맞은 문제를 count해 벡터에 저장
int num1 = 0;
int num2 = 0;
int num3 = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
for(int i=0; i<answers.size(); i++) {
if(s1[num1]==answers[i])
count1++;
if(s2[num2]==answers[i])
count2++;
if(s3[num3]==answers[i])
count3++;
num1++;
num2++;
num3++;
if(num1==5)
num1 = 0;
if(num2==8)
num2 = 0;
if(num3==10)
num3 = 0;
}
temp.push_back(count1);
temp.push_back(count2);
temp.push_back(count3);
//맞힌 문제 수 중 최댓값 구하기
int max = 0;
for(int i=0; i<3; i++) {
if(max<=temp[i])
max = temp[i];
}
//가장 문제를 많이 맞힌 사람 배열에 담기
for(int i=0; i<3; i++) {
if(max==temp[i])
answer.push_back(i+1);
}
//오름차순 정렬
sort(answer.begin(), answer.end());
return answer;
}
'프로그래머스' 카테고리의 다른 글
| 더 맵게 - 프로그래머스, c++ (0) | 2023.02.01 |
|---|---|
| 소수 찾기 - 프로그래머스, c++ (0) | 2023.01.31 |
| H-Index - 프로그래머스, c++ (0) | 2023.01.29 |
| 최소직사각형 - 프로그래머스, c++ (0) | 2023.01.28 |
| 가장 큰 수 - 프로그래머스, c++ (0) | 2023.01.28 |