알고리즘 - 완전탐색 - 수열 표현

mrtorture·2023년 12월 5일

최초 23/12/05

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

문제 요약

다음과 같은 수열이 있음
수열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, ...
정답 수열이 주어질 때 일치하는 숫자가 가장 많은 수열을 나열하기
ex){1, 2, 3, 4, 5} > {1}
ex){1, 3, 2, 4, 2} > {1, 2, 3}

준비물

연산자 관련: %, /
문법 관련: switch case
자료형 관련: Array.length; ArrayList.size(), ArrayList.add(), ArrayList.get()
디버깅 관련: 메모장에 예제 쓰는 습관

구현

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

class Solution {
    public int[] solution(int[] correct) {
        int[] student1 = new int[correct.length];
        for (int i = 0; i < student1.length; i++){
            student1[i] = i % 5 + 1;
        }
        
        int[] student2 = new int[correct.length];
        for (int i = 0; i < student2.length; i++) {
            if (i % 2 == 0) {
                student2[i] = 2;
            } else {
                switch (i % 8 / 2) {
                    case 0:
                        student2[i] = 1;
                        break;
                    case 1:
                        student2[i] = 3;
                        break;
                    case 2:
                        student2[i] = 4;
                        break;
                    default:
                        student2[i] = 5;
                }
            }
        }
        
        int[] student3 = new int[correct.length];
        for (int i = 0; i < student3.length; i++) {
            switch (i % 10 / 2) {
                case 0:
                    student3[i] = 3;
                    break;
                case 1:
                    student3[i] = 1;
                    break;
                case 2:
                    student3[i] = 2;
                    break;
                case 3:
                    student3[i] = 4;
                    break;
                default:
                    student3[i] = 5;
            }
        }
        
        int[] count = new int[3];
        for (int i = 0; i < correct.length; i++) {
            if (student1[i] == correct[i]) {
                count[0]++;
            }
            if (student2[i] == correct[i]) {
                count[1]++;
            }
            if (student3[i] == correct[i]) {
                count[2]++;
            }
        }
        
        int max = 0;
        for (int i = 0; i < 3; i++) {
            if (count[i] > max) {
                max = count[i];
            }
        }
        
        List<Integer> resultList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            if (count[i] == max) {
                resultList.add(i + 1);
            }
        }
        
        int[] result = new int[resultList.size()];
        for (int i = 0; i < result.length; i++) {
            result[i] = resultList.get(i);
        }
        
        return result;
    }
}
profile
명확하게 생각하고 싶다

0개의 댓글