By Java Lambda and Stream APIs


  • 0
    X
    final Map<Integer, Integer> occurencesMap = new HashMap<>();
    IntStream.of(nums1).forEach(e -> occurencesMap.compute(e, (k, oldVal) -> oldVal == null ? 1 : oldVal + 1));
    return IntStream.of(nums2).filter(e -> occurencesMap.computeIfPresent(e, (k, v) -> v == 0 ? null : v - 1) != null).toArray();
    

    or simplier By Multiset. I think it's really useful and should be added to JDK

    final Multiset<Integer> occurences = new Multiset<>();
    IntStream.of(nums1).forEach(e -> occurences.add(e));
    return IntStream.of(nums2).filter(e -> occurences.getAndRemove(e) > 0).toArray();
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.