[ 문제 ] : https://programmers.co.kr/learn/courses/30/lessons/42840

 

코딩테스트 연습 - 모의고사

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

programmers.co.kr


[ 문제 접근 ]

 

Lev.1 로 어렵지 않았던 문제.

 

1,2,3번 수포자의 패턴을 입력으로 들어오는 answers과 비교하면서 정답 횟수를 카운트 해나가면 된다.

 

문제 지문에 

가장 높은 점수를 받은 사람이 여럿일 경우, return하는 값을 오름차순 정렬해주세요.

라는 조건이 있어서 같은 값이 2개 이상일 때를 카운트 하여 따로 처리해주려고 했으나, 굳이 안해줬어도 상관 없었다.


[ 최종 코드 ]

 

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

using namespace std;

int first[] = { 1,2,3,4,5 };
int second[] = { 2,1,2,3,2,4,2,5 };
int third[] = { 3,3,1,1,2,2,4,4,5,5 };

int f_cnt, s_cnt, t_cnt; // 수포자 1,2,3이 맞힌 횟수.

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

	int f_length = sizeof(first) / sizeof(first[0]);
	int s_length = sizeof(second) / sizeof(second[0]);
	int t_length = sizeof(third) / sizeof(third[0]);

	for (size_t i = 0; i < answers.size(); i++) {
		int correct = answers[i];

		if (first[i%f_length] == correct) f_cnt++;
		if (second[i%s_length] == correct) s_cnt++;
		if (third[i%t_length] == correct) t_cnt++;

	}
	vector<int> temp(3);
	temp[0] = f_cnt;
	temp[1] = s_cnt;
	temp[2] = t_cnt;

	if (count(temp.begin(), temp.end(), *max_element(temp.begin(), temp.end())) >= 2) {
		int max = *max_element(temp.begin(), temp.end());
        for(int i=0;i<3;i++){
            if (max == temp[i]) answer.push_back(i+1);
        }
	}
	else {
		answer.push_back(max_element(temp.begin(), temp.end()) - temp.begin() + 1);
	}
	
	return answer;
}

 

 

 


[ Key Point ]

 

👉 이 부분을 

 

if (count(temp.begin(), temp.end(), *max_element(temp.begin(), temp.end())) >= 2) {
		int max = *max_element(temp.begin(), temp.end());
        for(int i=0;i<3;i++){
            if (max == temp[i]) answer.push_back(i+1);
       	   }
	}
	else {
		answer.push_back(max_element(temp.begin(), temp.end()) - temp.begin() + 1);
	}

 

아래와 같이 해줬어도 정답.

 

int max = *max_element(temp.begin(), temp.end());
for(int i=0;i<3;i++){
   if (max == temp[i]) answer.push_back(i+1);
}

 


[ 다른 사람 풀이 ]

 

ref :: https://rile1036.tistory.com/28

ref :: https://mungto.tistory.com/28

+ Recent posts