[프로그래머스/Java] 모의고사

Yujin·2025년 6월 18일

CodingTest

목록 보기
20/51

문제

https://school.programmers.co.kr/learn/courses/30/lessons/42840


문제풀이 방법

  1. 1번수포자, 2번수포자, 3번수포자가 찍는 번호 중 반복되는 값들을 추출
  2. answers 배열의 길이를 answer1,2,3으로 각각 나누어 index로 지정 후 값이 같으면 cnt++
  3. cnt1, cnt2, cnt3에서 가장 큰 값을 추출하여 그 사람의 번호를 list에 추가
  4. 만약 최댓값과 나머지 값들 중 같은 값이 있으면 같은 사람의 번호도 추가

나의 코드

import java.util.*;

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 % answer1.length]) 
                cnt1++;
            if (answers[i] == answer2[i % answer2.length]) 
                cnt2++;
            if (answers[i] == answer3[i % answer3.length]) 
                cnt3++;
        }
        
        int[] scores = {cnt1, cnt2, cnt3};
        int max = Math.max(cnt1, Math.max(cnt2, cnt3));
        
        List<Integer> list = new ArrayList<>();
        if (max == cnt1) list.add(1);
        if (max == cnt2) list.add(2);
        if (max == cnt3) list.add(3);
        
        int[] answer = new int[list.size()];
        for (int i = 0; i < answer.length; i++) {
            answer[i] = list.get(i);
        }
        return answer;
    }
}

0개의 댓글