99클럽 코테 스터디 15일차 TIL - 완전탐색

김동하·2024년 8월 5일
0

알고리즘

목록 보기
63/90

문제

[모의고사]

풀이

  • 세 학생의 답지 순서를 정적으로 생성한다. 반복될 것이니까 나머지 연산으로 처리하면 된다
  • answers와 대조할 함수를 만들고 각각 함수를 통해서 몇 개를 맞았는지 추출한다
  • 세 학생의 답안지를 순회하면서 몇 개 맞았는지 체크하고, max인 답안만 배열에 넣는다.

코드

import java.util.ArrayList;
import java.util.List;

class Solution {
    int[] answers;
    
    public List<Integer> solution(int[] answers) {
        this.answers = answers;
        List<Integer> answer = new ArrayList<>();

        int[] s1 = new int[]{1, 2, 3, 4, 5};
        int[] s2 = new int[]{2, 1, 2, 3, 2, 4, 2, 5};
        int[] s3 = new int[]{3, 3, 1, 1, 2, 2, 4, 4 ,5, 5};
        int[][] sArr = new int[][]{s1, s2, s3};
        int max = 0;
        
        for(int i = 0; i < sArr.length; i++){
            int score = checkAnswer(sArr[i]);
            if(max < score){
                answer.clear();
                answer.add(i + 1);
                max = score;
            } else if (score == max) {
                answer.add(i + 1);
            }
        } 
        
        return answer;
    }
    
    public int checkAnswer(int[] arr){
        int cnt = 0;
        for(int i = 0; i < this.answers.length; i++){
            if(arr[i % arr.length] == this.answers[i]) cnt++;
        }
        return cnt;
    }
}

정리

profile
프론트엔드 개발

0개의 댓글