본문 바로가기

today I learned/algorithm

[해시] 폰켄몬

문제

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

풀이

import java.util.*;
import java.util.stream.Collectors;

class Solution {
    public int solution(int[] nums) {
        /*
        1) 배열의 distinct 수를 구함 
        2-1) 그 수가 N/2 이상이면
        N/2출력
        
        2-2) 그 수가 N/2 미만이면
        distinct의 count 출력
        */
        int nDivTwo = nums.length / 2;
        Set<Integer> set = Arrays.stream(nums)
                        .boxed()
                        .collect(Collectors.toSet());
        
        if(set.size() >= nDivTwo){
            return nDivTwo;
        }
        return set.size();
    }
}

 

폰켄몬을 함수형 프로그래밍으로 구현하자.

return Arrays.stream(nums)
                        .boxed()
                        .collect(Collectors.collectingAndThen(Collectors.toSet(),
                                phonekemons -> Integer.min(phonekemons.size(), nums.length / 2 )));

 

여기서 Collectors.collectingAndThen 이란 ? 

Collecting을 진행한 후, 그 Collector을 기반으로 메서드를 호출하여 Return값을 받음. 위의 코드는 nums를 Set로 Collecting한 후, 이 Collector를 활용하여 min값을 리턴하였다.

 

풀이

홍박사님이 얻고싶은 최대 값은 N/2.

여기서 중복이 있을 경우 N/2보다 작아질 수 있는데, 

1) 겹치지 않는 숫자 개수의 합이 N/2보다 클 경우는 N/2값을 모두 가질 수 있으므로 N/2 리턴

2) 겹치지 않는 숫자 개수의 합이 N/2보다 작을 경우는 중복제거한 만큼의 값을 가질 수 있으므로 Set(nums).size() 리턴

'today I learned > algorithm' 카테고리의 다른 글

[DFS] 타겟넘버  (0) 2024.04.07
[해시] 전화번호 목록  (0) 2023.10.05