[프로그래머스/Level1] 로또의 최고 순위와 최저 순위

SeokHyun·2022년 7월 7일
0

프로그래머스

목록 보기
17/32

문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/77484

문제 접근

핵심은 맞은 개수와 0의 개수를 카운팅하는 것이다.

맞은 개수만으로 최저 등수가 나오고, 맞은 개수 + 0의 개수로 최고 등수를 판별하는 문제이다.

나는 각각의 개수를 stream을 이용해서 했는데, for에 비해서 속도가 느렸다.

평소 stream이 가독성이 높아 더 선호하기 때문에 로직 짤 때도 stream이 먼저 떠오른다...

소스 코드

import java.util.*;

class Solution {
    public int[] solution(int[] lottos, int[] win_nums) {
        int[] answer = new int[2];
        
        //이진 탐색을 위해 win_nums 정렬
        Arrays.sort(win_nums);
        
        //0 갯수 카운팅
        int zeroCount = (int) Arrays.stream(lottos)
            .filter(lotto -> lotto == 0)
            .count();
        //모두 0이면 1, 6 저장 후 종료
        if (zeroCount == 6) {
            answer[0] = 1;
            answer[1] = 6;
            
            return answer;
        }
        
        //맞은 번호 갯수 카운팅
        int winCount = (int) Arrays.stream(lottos)
            .filter(lotto -> Arrays.binarySearch(win_nums, lotto) >= 0)
            .count();
        
        //최대, 최소 등수 판별
        answer[0] = Math.min(6, 7 - winCount - zeroCount);
        answer[1] = Math.min(6, 7 - winCount);
        
        return answer;
    }
}
profile
SI를 넘어 백엔드 엔지니어를 향하여

0개의 댓글