프로그래머스 - 모의고사 (Level 1)

2024. 1. 11. 17:08코딩테스트 정리(자바)

728x90

막연한 풀이

class Solution {
    public static int[] one={1,2,3,4,5};
    public static int[] two={2,1,2,3,2,4,2,5};
    public static int[] three={3,3,1,1,2,2,4,4,5,5};
    
    public int score(int[] answer,int[] answers){
        int score=0;
        int len=answer.length;
        for(int i=0;i<answers.length;i++){
            if(answer[i%len]==answers[i]) //찍은 길이가 다 다르므로 배열의 길이로 나머지 연산
                score++;
        }
        return score;
    }
    public int[] solution(int[] answers) {
    
        int result1 =score(one,answers);
        int result2=score(two,answers);
        int result3=score(three,answers);
        
       if(result1>result2){
           if(result1>result3)
               return new int[]{1};
           else if(result3>result1)
               return new int[]{3};
           else
               return new int[]{1,3};
       }
        else if(result2>result1){
            if(result2>result3)
                return new int[]{2};
            else if(result3>result2)
                return new int[]{3};
            else
                return new int[]{2,3};
        }
        else{
            if(result1>result3)
               return new int[]{1,2};
           else if(result3>result1)
               return new int[]{3};
           else
               return new int[]{1,2,3};
        }
           
    }
}

 

 

조금 간결해진 풀이

import java.util.*;
class Solution {
    public static int[] one={1,2,3,4,5};
    public static int[] two={2,1,2,3,2,4,2,5};
    public static int[] three={3,3,1,1,2,2,4,4,5,5};
    
    public int score(int[] answer,int[] answers){
        int score=0;
        int len=answer.length;
        for(int i=0;i<answers.length;i++){
            if(answer[i%len]==answers[i])
                score++;
        }
        return score;
    }
    public int[] solution(int[] answers) {
    
        int result1 =score(one,answers);
        int result2=score(two,answers);
        int result3=score(three,answers);
        
       List<Integer> result=new ArrayList<>();
        int max=Math.max(result1,Math.max(result2,result3));
        if(max==result1)
            result.add(1);
        if(max==result2)
            result.add(2);
        if(max==result3)
            result.add(3);
        
        return result.stream().mapToInt(i->i).toArray(); //리스트를 배열로
           
    }
}

 

 

1. Math.max()는 인자가 2개뿐
-> 2개씩만 비교가능

 

2. Integer 타입의 리스트를 배열로 변경하는 방법

: 1.  stream으로 변경 후

2. IntStream으로 변경

람다 식을 사용한 자동 언박싱  mapToInt(i->i) 

-> 이 암시적 언박싱은 컴파일러가 이 람다의 결과가 int여야 한다고 결정할 수 있기 때문에 작동한다.

3. 그 후 toArray()

 

그러나 스트림연산은 시간이 오래 걸린다.

따라서 아래와 같이 for문을 통해 바꾸는 것이 더 빠르다.

int[] answer = new int[result.size()];
for (int i = 0; i < answer.length; i++)
    answer[i] = result.get(i);

return answer;

 

 

728x90