코딩테스트 연습

폰켓몬을 받을때 최대 몇 종류를 가져갈 수 있을까?

고유빙글 2021. 8. 20. 05:39
public class phoneGetMon {

	public static void main(String[] args) {
		
		int[] nums = {3,1,2,3};
		int answer = solution(nums);
		System.out.println(answer);
		
	}

	private static int solution(int[] nums) {
		int answer = 0;
		int count = 0;
		
		for (int i = 0; i < nums.length; i++) {
			for (int j = i+1; j < nums.length; j++) {
				if(nums[i]==nums[j]) {
					nums[j] = -1;
				}
			}
			if(nums[i]!=-1) {
				count++;
			}
		}
		
		System.out.println("count : "+count);
		System.out.println("nums.length/2 : "+nums.length/2);
		if(count>nums.length/2) {
			answer=nums.length/2;
		}else {
			answer=count;
		}
		
		return answer;
	}

}

문제가 많이 간단했다.

하지만 문제는...다른 사람의 풀이는 나보다 더 간단했다!

 

stream과 collector를 사용했던데 어떤건지 너무 낯설다.. 찾아봐야겠다

 

===============================================

map이나 set을 이용하면 중복을 제거할 수 있는데 이것또한 응용할 수 있었겠다..

 

참고한 다른 사람의 풀이이다..

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)));
    }
}