Simple code by Java 8 Stream/Map API


  • 0
    X
    public int[] intersect(int[] nums1, int[] nums2) {
        final Map<Integer, Integer> occursMap = new HashMap<>();
        IntStream.of(nums1).forEach(i -> occursMap.compute(i, (k, v) -> v == null ? 1 : v + 1));
        return IntStream.of(nums2).filter(i -> occursMap.computeIfPresent(i, (k, v) -> v == 0 ? null : v - 1) != null).toArray();
    }
    

Log in to reply
 

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