[코딩테스트] [프로그래머스] 모의고사

김민정·2025년 9월 19일
1

코딩테스트

목록 보기
27/33
post-thumbnail

문제

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


풀이

풀이

  1. 찍는 패턴 순서대로 벡터 만들어두고, index % 각 벡터 size를 인덱스로 하여 answers 값과 비교한다.
    1-1. answers 값과 비교하여 scores 벡터 업데이트

  2. scores 중 최댓값 도출

  3. 최대 score과 동일하다면, 현재 index + 1 수포자가 가장 높은 점수를 획득했다는 뜻이기에 answer 벡터에 index + 1 넣어준다.

주의점

  1. 찍는 패턴 벡터 초기화를 잘못 해서 정확성 검사 통과를 못했다.. 문제 확인을 꼼꼼히 하도록 하자...

코드

#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<int> solution(vector<int> answers) 
{
    vector<int> first = { 1, 2, 3, 4, 5 };
    vector<int> second = { 2, 1, 2, 3, 2, 4, 2, 5 };
    vector<int> third = { 3, 3, 1, 1, 2, 2, 4, 4, 5, 5 };
    
    vector<int> scores(3, 0);
    for (int i=0; i<answers.size(); i++)
    {
        if(answers[i] == first[i % first.size()])
            scores[0]++;
        
        if(answers[i] == second[i % second.size()])
            scores[1]++;
        
        if(answers[i] == third[i % third.size()])
            scores[2]++;
    }
    
    int maxScore =0;
    for(int i=0; i<scores.size(); i++)
    {
        if(maxScore < scores[i])
            maxScore = scores[i];
    }
    
    vector<int> answer;
    for(int i=0; i<scores.size(); i++)
    {
        if(maxScore == scores[i])
            answer.push_back(i + 1);
    }
    
    return answer;
}

다른 풀이와 코드

  1. max score를 구할 때, std::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> thr = {3,3,1,1,2,2,4,4,5,5};

vector<int> solution(vector<int> answers) 
{
    vector<int> answer;
    vector<int> they(3);
    for(int i=0; i<answers.size(); i++) 
    {
        if(answers[i] == one[i%one.size()]) they[0]++;
        if(answers[i] == two[i%two.size()]) they[1]++;
        if(answers[i] == thr[i%thr.size()]) they[2]++;
    }
    int they_max = *max_element(they.begin(),they.end());
    for(int i = 0; i< 3; i++) 
    {
        if(they[i] == they_max) answer.push_back(i+1);
    }
    return answer;
}
profile
📝 공부노트

0개의 댓글