우주먼지

💡 문제 파악

포켓몬의 종류가 담긴 배열 nums가 있고 이 배열의 길이를 이용해 최댓값(nums / 2)을 구할 수 있다.

 

풀이

  1. 최대값을 구하기 위해 주어진 배열 nums의 length를 2로 나눈 값을 max에 대입한다.
  2. 중복을 제거한 값을 구하기 위해 Set을 이용해서 nums에 있는 값들을 담아준다.
    → 이때, Set은 집합 기반이기에 중복을 알아서 제거하며, 빠른 탐색을 위해 HashSet을 이용하였다.
  3. 중복을 제거한 Set의 크기가 max보다 크면 max를, 작으면 Set 사이즈를 리턴한다.

 

코드

import java.util.HashSet;

public class Solution {
    public int solution(int[] nums) {
        // 총 수에 2를 나눔
        int max = nums.length / 2;

        // 중복을 제거하는 Integer HashSet 생성
        HashSet<Integer> hashSet = new HashSet<>();

        // Set에 데이터를 넣음으로서 중복된 데이터를 제거 한다
        for (int n : nums) {
            hashSet.add(n);
        }

        // 중복을 제거한 Set의 크기가 max보다 크면 max, 작으면 set 사이즈 리턴
        if (max >= hashSet.size()) {
            return hashSet.size();
        } else {
            return max;
        }
    }
}

 

다른사람의 풀이

import java.util.Arrays;
import java.util.stream.Collectors;

class Solution {
    public int solution(int[] nums) {
        return Arrays.stream(nums)
            .boxed()
            .collect(Collectors.collectingAndThen(Collectors.toSet(),
               phonekemons -> Integer.min(phonekemons.size(), nums.length / 2)));
    }
}
profile

우주먼지

@o귤o

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그