https://school.programmers.co.kr/learn/courses/30/lessons/42840?language=cpp
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
C++ 코드
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> answers) {
vector<int> answer;
vector<vector<int>> all_student;
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};
all_student.push_back(one);
all_student.push_back(two);
all_student.push_back(three);
for (auto i : all_student )
{
int count = 0;
for ( int j = 0 ; j < answers.size(); j++)
{
if (answers[j] == i[j%i.size()])
{
count++;
}
}
answer.push_back(count);
}
int biggest = *max_element(answer.begin(),answer.end());
vector<int> realanswer;
int idx = 1;
for (auto i : answer)
{
if (biggest == i)
{
realanswer.push_back(idx);
}
idx++;
}
return realanswer;
}
다른 인원 풀이 :
#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;
}
저와 알고리즘 자체는 같지만 훨씬 더 세련되게 C++ 코드를 작성했기에 학습용으로 기재합니다.
파이썬 코드 :
def solution(answers):
answer = []
check = [0] *3
one = [1,2,3,4,5]
two = [2,1,2,3,2,4,2,5]
three = [3,3,1,1,2,2,4,4,5,5]
for i in range(len(answers)):
if answers[i] == one[i%len(one)]:
check[0] += 1
if answers[i] == two[i%len(two)]:
check[1] += 1
if answers[i] == three[i%len(three)]:
check[2] += 1
best = max(check)
for index,value in enumerate(check):
if value == best:
answer.append(index+1)
return answer
근본적인 알고리즘은 둘 다 맞다 C++은 구현에 치중하기위해 일부로 vector<int>자료형을 갖는 벡터로 구현하려 해보았다.
그리고 레벨 1이라 그런진 모르겠지만, 뭔가 완전 탐색이 구현문제처럼 다가왔다.
'코딩 테스트 > 프로그래머스' 카테고리의 다른 글
Lv.2 ( 스택/큐 ) 올바른 괄호 - Python (1) | 2023.10.14 |
---|---|
Lv2.(깊이/너비 우선 탐색) 게임 맵 최단거리 - C++ (0) | 2023.05.06 |
Lv.3 ( 해시 ) 베스트앨범 - C++ (0) | 2023.05.05 |
Lv2.(해시) 의상 - C++ (0) | 2023.05.05 |
Lv2.(해시) 전화번호 목록 - C++ (0) | 2023.05.05 |