以下の内容はhttps://su-kun1899.hatenablog.com/entry/2020/02/10/125837より取得しました。


961. N-Repeated Element in Size 2N Array

LeetCode の挑戦ログ

Problem

https://leetcode.com/problems/n-repeated-element-in-size-2n-array/

  • 2N サイズの配列が与えられる
  • N+1 種類の整数が含まれている
  • 一つの要素が N 回繰り返されている
  • N 回繰り返されてる数を特定する

Solution

class Solution {
    public int repeatedNTimes(int[] A) {
        return Arrays.stream(A).boxed()
                .collect(Collectors.groupingBy(i -> i, Collectors.counting()))
                .entrySet().stream()
                .filter(it -> it.getValue() == A.length / 2)
                .map(Map.Entry::getKey)
                .findAny()
                .orElse(0);
    }
}

Impressions

  • Collectors.groupingByCollectors.counting() を組み合わせることで、Key ごとの数という Map が作れる
    • collect(Collectors.groupingBy(i -> i, Collectors.counting()))
  • 本当は groupingBy のところを自前で書くような問題なんだろう

References




以上の内容はhttps://su-kun1899.hatenablog.com/entry/2020/02/10/125837より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14