모의고사 (자바)

김재현·2023년 11월 24일
0

알고리즘 풀이

목록 보기
28/89
post-thumbnail

문제

정답 코드

import java.util.*;

class Solution {
    public int[] solution(int[] answers) {
        int a=0;
        int b=0;
        int c=0;

        int[] arrA={1,2,3,4,5};
        int[] arrB={2,1,2,3,2,4,2,5};
        int[] arrC={3,3,1,1,2,2,4,4,5,5};

        for(int i=0;i<answers.length;i++) {
            if(answers[i]==arrA[i%5]) {
                a++;
            }
            if (answers[i]==arrB[i%8]) {
                b++;
            }
            if (answers[i]==arrC[i%10]) {
                c++;
            }
        }

        int[] arr = {a,b,c};
        int max=0;
        for(int i=0;i<3;i++) {
            if(max<=arr[i]) {max=arr[i];}
        }

        List<Integer> arrList = new ArrayList<>();

        for (int i=0;i<arr.length;i++) {
            if (max==arr[i]) { arrList.add(i+1);}
        }

        int[] answer = new int[arrList.size()];
        for(int i=0;i<arrList.size();i++) {
            answer[i]=arrList.get(i);
        }

        return answer;
    }
}

처음에 a,b,c로 각각의 수포자의 점수는 잘 구했지만 어떻게 점수를 나열해야할지 막막했다.

결국 스터디에서 다른 분께서 List로 바꿨다가 다시 배열로 바꾸는 것을 보고 나도 그렇게 해봤다.
이렇게 돌아돌아 가는게 맞는걸까, 다른 방법은 없을까 하여 다른 사람들의 풀이도 찾아봤지만 다들 비슷하게 풀이 한 것으로 보인다.

자바의 한계인가... 스터디에서 파이썬은 금방 풀던데! 하하

다른 사람 코드


import java.util.ArrayList;
class Solution {
    public int[] solution(int[] answer) {
        int[] a = {1, 2, 3, 4, 5};
        int[] b = {2, 1, 2, 3, 2, 4, 2, 5};
        int[] c = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
        int[] score = new int[3];
        for(int i=0; i<answer.length; i++) {
            if(answer[i] == a[i%a.length]) {score[0]++;}
            if(answer[i] == b[i%b.length]) {score[1]++;}
            if(answer[i] == c[i%c.length]) {score[2]++;}
        }
        int maxScore = Math.max(score[0], Math.max(score[1], score[2]));
        ArrayList<Integer> list = new ArrayList<>();
        if(maxScore == score[0]) {list.add(1);}
        if(maxScore == score[1]) {list.add(2);}
        if(maxScore == score[2]) {list.add(3);}
        return list.stream().mapToInt(i->i.intValue()).toArray();
    }
}

개념은 같지만 return부분이 독보적이었다.
stream과 map, 그리고 람다를 이용해서 list를 배열로 바꾸다니 멋있다!

profile
I live in Seoul, Korea, Handsome

0개의 댓글