This is perhaps not the fastest solution, but it's just beautiful


  • 2
    J
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> intersect = IntStream.of(nums1).boxed()
            .collect(Collectors.toSet());
        intersect
            .retainAll(IntStream.of(nums2).boxed().collect(Collectors.toSet()));
        return intersect.stream().mapToInt(x -> x).toArray();
    }
    

    This is a illustration how strong Java 8 is. You can write 5 lines to do this while it'll take 15 lines or so in Java 7. With IntStream you can totally get away from all the manual boxing/unboxing.


  • 0
    W
    Beautiful code... I had something similar but changed mine to this:
    
    public int[] intersection(int[] nums1, int[] nums2) {
            
           return IntStream.of( nums1 ).boxed().collect(Collectors.toList()).stream().filter( IntStream.of( nums2 ).boxed().collect(Collectors.toList())::contains  ).collect(Collectors.toSet()).stream().mapToInt(u -> u).toArray();
            
        }

  • 0
    J

    I like the filter use here


  • 0

    "it'll take 15 lines or so in Java 7"

    public int[] intersection2(int[] nums1, int[] nums2) {
        Set<Integer> a = new HashSet<>(), b = new HashSet<>();
        for (int x : nums1) a.add(x);
        for (int x : nums2) b.add(x);
        a.retainAll(b);
        int out[] = new int[a.size()], i = 0;
        for (int x : a) out[i++] = x;
        return out;
    }

  • 0
    J

    True you can always shorten the code somehow, but let's say you use complete for loops (with curly brackets before and after) for each of the three statement here and put each declaration of variable on a separate line, it actually takes 15 lines exactly according to your provided code.

    Here I wasn't referring to a Java 7 code that tries to minimize LOC as much as possible anyway, I actually split a line into two once it's over 80 characters and that's why I'm counting 5 instead of 3.

    BTW, I do like a LOT of answers you posted here.


  • 0

    Well you're really maximizing my LOC there, that's not what I'd call "it'll take". It "takes" 15 lines only for someone who loves wasting space :-)


Log in to reply
 

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