🍀 문제
수포자는 수학을 포기한 사람의 준말입니다. 수포자 삼인방은 모의고사에 수학 문제를 전부 찍으려 합니다. 수포자는 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하는 값을 오름차순 정렬해주세요.
입출력 예
[1,2,3,4,5] | [1] |
[1,3,2,4,2] | [1,2,3] |
https://programmers.co.kr/learn/courses/30/lessons/42840
코딩테스트 연습 - 모의고사
수포자는 수학을 포기한 사람의 준말입니다. 수포자 삼인방은 모의고사에 수학 문제를 전부 찍으려 합니다. 수포자는 1번 문제부터 마지막 문제까지 다음과 같이 찍습니다. 1번 수포자가 찍는 ��
programmers.co.kr
나의 코드 😊
class Solution {
public int[] solution(int[] answers) {
int answer1[] = { 1, 2, 3, 4, 5 };
int answer2[] = { 2, 1, 2, 3, 2, 4, 2, 5 };
int answer3[] = { 3, 3, 1, 1, 2, 2, 4, 4, 5, 5 };
// 맞춘 갯수
int cnt1 = 0;
int cnt2 = 0;
int cnt3 = 0;
for (int i = 0; i < answers.length; i++) {
if (answers[i] == answer1[i % 5]) {
cnt1++;
}
if (answers[i] == answer2[i % 8]) {
cnt2++;
}
if (answers[i] == answer3[i % 10]) {
cnt3++;
}
}
int max = Math.max(cnt1, cnt2);
max = Math.max(cnt3, max);
String answerList = "";
if (cnt1 == max) {
answerList += "1";
}
if (cnt2 == max) {
answerList += "2";
}
if (cnt3 == max) {
answerList += "3";
}
int[] answer = new int[answerList.length()];
for (int i = 0; i < answerList.length(); i++) {
answer[i] = answerList.charAt(i) - '0';
}
return answer;
}
}
멋진 다른 사람의 코드😎
import java.util.ArrayList;
class Solution {
public int[] solution(int[] answer) {
int[] a = {1, 2, 3, 4, 5};
int[] b = {2, 1, 2, 3, 2, 4, 2, 5};
int[] c = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
int[] score = new int[3];
for(int i=0; i<answer.length; i++) {
if(answer[i] == a[i%a.length]) {score[0]++;}
if(answer[i] == b[i%b.length]) {score[1]++;}
if(answer[i] == c[i%c.length]) {score[2]++;}
}
int maxScore = Math.max(score[0], Math.max(score[1], score[2]));
ArrayList<Integer> list = new ArrayList<>();
if(maxScore == score[0]) {list.add(1);}
if(maxScore == score[1]) {list.add(2);}
if(maxScore == score[2]) {list.add(3);}
return list.stream().mapToInt(i->i.intValue()).toArray();
}
}
다른 사람 코드를 보니 맞춘갯수를 cnt1,cnt2,cnt3로 두지 않고 score[3]처럼 배열을 쓸걸!이라는 생각이 들었다.
'알고리즘 > 프로그래머스' 카테고리의 다른 글
프로그래머스 LV2. 프린터 (0) | 2020.08.24 |
---|---|
프로그래머스 LV1. 체육복 (0) | 2020.08.20 |
프로그래머스 LV1. 문자열 내 마음대로 정렬하기 자바 (0) | 2020.08.14 |
프로그래머스 LV1. 같은 숫자는 싫어 (0) | 2020.08.14 |
프로그래머스 LV1. 2016년 (0) | 2020.08.14 |
댓글