1207. Unique Number of Occurrences

LeetCode の挑戦ログ

Problem

https://leetcode.com/problems/unique-number-of-occurrences/

  • 整数の配列を渡される
  • 値の登場回数がユニークで構成される場合は true を返す

Solution

class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        Map<Integer, Long> map = Arrays.stream(arr)
                .boxed()
                .collect(Collectors.groupingBy(i -> i, Collectors.counting()));

        int valueCount = map.size();
        long occurrenceCount = map.values().stream().distinct().count();

        return valueCount == occurrenceCount;
    }
}

Impressions

  • 要素の数を数えたいときは、 Collectors#groupingBy の第 2 引数に Collectors.counting() を渡す

References