[LeetCode] Unique Number of Occurrences

아르당·1일 전

LeetCode

목록 보기
252/254
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

정수 배열 arr이 주어졌을 때, 배열에 있는 각 값들이 발생한 수가 고유하다면 true, 그렇지 않다면 false를 반환해라.

Example

#1
Input: arr = [1, 2, 2, 1, 1, 3]
Output: true
Explanation: 값 1은 3번 발생하고, 2는 2, 3은 1번 발생한다. 같은 수로 발생하는 값이 없다.

#2
Input: arr = [1, 2]
Output: false

#3
Input: arr = [-3, 0, 1, -3, 1, 1, 1, -3, 10, 0]
Output: true

Constraints

  • 1 <= arr.length <= 1000
  • -1000 <= arr[i] <= 1000

Solved

class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        Map<Integer, Integer> nums = new HashMap<>();

        for(int num : arr){
            nums.put(num, nums.getOrDefault(num, 0) + 1);
        }

        Set<Integer> set = new HashSet<>();

        for(int num : nums.values()){
            if(!set.add(num)){
                return false;
            }
        }

        return true;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글