알고리즘 풀이/프로그래머스

[level1] 프로그래머스 - 폰켓몬(JAVA)

데롱디롱 2021. 8. 27. 01:55
728x90

- 포켓몬 이름을 key로 갖는 map에 각 포켓몬의 등장 횟수를 value로 저장

- 포켓몬 종류가 전체 포켓몬 수/2 보다 크다면 답은 전체 포켓몬 수/2

- 포켓몬 종류 수가 더 작다면 답은 포켓몬 종류 개수

 

 

import java.util.HashMap;

class Solution {
    public int solution(int[] nums) {
        HashMap<Integer, Integer> ponketmon = new HashMap<Integer, Integer>();
		for (int i = 0; i < nums.length; i++) {
			if (ponketmon.containsKey(nums[i]))
				ponketmon.put(nums[i], ponketmon.get(nums[i]) + 1);
			else
				ponketmon.put(nums[i], 1);
		}

		return ponketmon.size() > nums.length / 2 ? nums.length / 2 : ponketmon.size();
    }
}