[레벨1] 모의고사 (JAVA)

Fekim·2022년 3월 15일
0

ps

목록 보기
44/48
  • 각각의 수포자가 문제를 찍는 패턴이 일정하므로, 순환하는 구조이다
    -> Queue를 활용하여 풀어보았다
import java.util.*;

class Solution {
    public int[] solution(int[] answers) {
        // 맞은 갯수가 들어갈 배열
        int[] values = new int[3];
        
        // 큐로 풀자
        Queue<Integer> supoA = new LinkedList<>();
        supoA.offer(1);
        supoA.offer(2);
        supoA.offer(3);
        supoA.offer(4);
        supoA.offer(5);
        Queue<Integer> supoB = new LinkedList<>();
        supoB.offer(2);supoB.offer(1);
        supoB.offer(2);supoB.offer(3);
        supoB.offer(2);supoB.offer(4);
        supoB.offer(2);supoB.offer(5);
        Queue<Integer> supoC = new LinkedList<>();
        supoC.offer(3);supoC.offer(3);
        supoC.offer(1);supoC.offer(1);
        supoC.offer(2);supoC.offer(2);
        supoC.offer(4);supoC.offer(4);
        supoC.offer(5);supoC.offer(5);
        
        // 맞은 개수 계산
        for(int i=0; i<answers.length; ++i){
            // 패턴이 반복되므로, Queue에서 poll -> offer 반복
            int tmp = supoA.poll();
            if(tmp == answers[i])
                values[0]++;
            supoA.offer(tmp);
            
            tmp = supoB.poll();
            if(tmp == answers[i])
                values[1]++;
            supoB.offer(tmp);
            
            tmp = supoC.poll();
            if(tmp == answers[i])
                values[2]++;
            supoC.offer(tmp);
            
        }
        
        // 최댓값 찾기
        int max = Integer.MIN_VALUE;
        for(int i : values){
            max = Math.max(max, i);
        }
        
        
        // 배열에서 최댓값에 해당하는 인덱스만 list에 담는다.
        ArrayList<Integer> list = new ArrayList<>();
        for(int i =0; i<values.length; ++i){
            if(values[i] == max)
                list.add(i+1);
        }
        
        // 리스트 정렬
        Collections.sort(list);
        
        // 리스트를 결과 배열로 변환
        int[] answer = new int[list.size()];
        for(int i=0; i<list.size(); ++i)
            answer[i] = list.get(i);
            
        return answer;
        
    }
}
profile
★Bugless 2024★

0개의 댓글