문제 링크 https://programmers.co.kr/learn/courses/30/lessons/42840

문제

수포자는 수학을 포기한 사람의 준말입니다. 수포자 삼인방은 모의고사에 수학 문제를 전부 찍으려 합니다. 수포자는 1번 문제부터 마지막 문제까지 다음과 같이 찍습니다.

1번 수포자가 찍는 방식: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, … 2번 수포자가 찍는 방식: 2, 1, 2, 3, 2, 4, 2, 5, 2, 1, 2, 3, 2, 4, 2, 5, … 3번 수포자가 찍는 방식: 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, …

1번 문제부터 마지막 문제까지의 정답이 순서대로 들은 배열 answers가 주어졌을 때, 가장 많은 문제를 맞힌 사람이 누구인지 배열에 담아 return 하도록 solution 함수를 작성해주세요.

제한사항

  • 시험은 최대 10,000 문제로 구성되어있습니다.
  • 문제의 정답은 1, 2, 3, 4, 5중 하나입니다.
  • 가장 높은 점수를 받은 사람이 여럿일 경우, return하는 값을 오름차순 정렬해주세요.

풀이 과정

이 문제는 완전탐색 문제로, 규칙을 찾아서 i % 5, i % 8, i % 10
인덱스에 있는 값과 같으면 카운트 해주면 된다.

가장 많은 문제를 맞힌 사람이 여럿일 경우 다 넣어줘야한다.
1, 2, 3 차례대로 넣기 때문에 오름차순으로 다시 정렬 안 해도 된다.

풀이1

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int num1[5] = {1, 2, 3, 4, 5};
int num2[8] = {2, 1, 2, 3, 2, 4, 2, 5};
int num3[10] = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
int cnt1, cnt2, cnt3;

vector<int> solution(vector<int> answers) {
    vector<int> answer;

    for(int i = 0; i < answers.size(); i++){
        if(answers[i] == num1[i % 5]) cnt1++;
        if(answers[i] == num2[i % 8]) cnt2++;
        if(answers[i] == num3[i % 10]) cnt3++;
    }

    int res = max({cnt1, cnt2, cnt3});
    if(res == cnt1) answer.push_back(1);
    if(res == cnt2) answer.push_back(2);
    if(res == cnt3) answer.push_back(3);

    return answer;
}

풀이2

#include <string>
#include <vector>

using namespace std;

int num1[5] = {1, 2, 3, 4, 5};
int num2[8] = {2, 1, 2, 3, 2, 4, 2, 5};
int num3[10] = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
int cnt1, cnt2, cnt3;

// max 함수 구현
int max(int x, int y){
    return x > y ? x : y;
}

vector<int> solution(vector<int> answers) {
    vector<int> answer;

    for(int i = 0; i < answers.size(); i++){
        if(answers[i] == num1[i % 5]) cnt1++;
        if(answers[i] == num2[i % 8]) cnt2++;
        if(answers[i] == num3[i % 10]) cnt3++;
    }

    int res = max(cnt1, cnt2);
    res = max(res, cnt3);

    if(res == cnt1) answer.push_back(1);
    if(res == cnt2) answer.push_back(2);
    if(res == cnt3) answer.push_back(3);

    return answer;
}

댓글남기기