import java.util.ArrayList;
public class Solution {
public int[] solution(int[] answers) {
int[] a = new int[] {1, 2, 3, 4, 5};
int[] b = new int[] {2, 1, 2, 3, 2, 4, 2, 5};
int[] c = new int[] {3, 3, 1, 1, 2, 2, 4, 4, 5, 5}; //제시된 정답규칙
int[] score = new int[3]; //세 학생의 점수 비교를 위한 배열
for (int i=0; i<answers.length; i++) { // 주어진 answers라는 정답 배열과 비교하여 점수 배열에 담기
if (answers[i] == a[i%5]) {score[0]++;} //각 학생의 정답패턴 길이에 맞게 나누어 비교
if (answers[i] == b[i%8]) {score[1]++;}
if (answers[i] == c[i%10]) {score[2]++;}
}
int max = Math.max(Math.max(score[0], score[1]),score[2]); // 세 학생의 점수중 최고점 도출
ArrayList<Integer> length = new ArrayList<Integer>();
if (max == score[0]) length.add(1); // 점수가 같을경우 List에 맞춰 담기
if (max == score[1]) length.add(2);
if (max == score[2]) length.add(3);
int[] answer = new int[length.size()]; // List의 길이만큼 answer 길이 설정
// answer배열에 List에 담긴 값 넣기
for (int i=0; i<answer.length; i++) { answer[i] = length.get(i); }
return answer;
}
}
2021.11.14 풀이
import java.util.*;
class Solution {
public int[] solution(int[] answers) {
int[] a = new int[] {1, 2, 3, 4, 5}; // 1번 패턴
int[] b = new int[] {2, 1, 2, 3, 2, 4, 2, 5}; // 2번 패턴
int[] c = new int[] {3, 3, 1, 1, 2, 2, 4, 4, 5, 5}; // 3번 패턴
int[] cnt = new int[3]; // 맞춘문제 cnt
int[] loop = new int[3]; // 각 패턴에 맞춰서 loop
for(int i=0; i<answers.length; i++) {
loop[0] = loop[0] < 5 ? loop[0] : 0; // 1번 패턴 loop 길이 설정
loop[1] = loop[1] < 8 ? loop[1] : 0; // 2번
loop[2] = loop[2] < 10 ? loop[2] : 0; // 3번 동일
if(answers[i] == a[loop[0]]) {cnt[0]++;}
if(answers[i] == b[loop[1]]) {cnt[1]++;}
if(answers[i] == c[loop[2]]) {cnt[2]++;}
loop[0]++;
loop[1]++;
loop[2]++;
}
ArrayList<Integer> list = new ArrayList<>();
// 3개의 패턴중 최대값 도출
int max = Math.max(Math.max(cnt[0], cnt[1]), cnt[2]);
// 최대값 중복인 패턴 확인
for(int i=0; i<3; i++) {
if(max == cnt[i]) {list.add(i+1);}
}
int[] answer = new int[list.size()];
// 가장 높은 점수 받은 사람들 다시 배열에 담고 리턴
for(int i=0; i<list.size(); i++) {
answer[i] = list.get(i);
}
return answer;
}
}
이전 풀이법이 시간복잡도가 더 빠르다..
[Programmers] Level1. 2016년 (Java) (0) | 2021.01.02 |
---|---|
[Programmers] Level1. K번째 수 (Java) (0) | 2021.01.01 |
[Programmers] Level1. 체육복 (Java) (0) | 2020.12.28 |
[Programmers] Level1. 완주하지 못한 선수 (Java) (0) | 2020.12.27 |
두 개 뽑아서 더하기 (0) | 2020.12.08 |