Add to List 349. Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2].

Note:

    • Each element in the result must be unique.
    • The result can be in any order.

给出两个数组,求他们的交集。出题的意图何在?

    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();
        Set<Integer> inter = new HashSet<>();
        for(int a:nums1)
            set.add(a);
        for(int a:nums2)
        {
            if(set.contains(a))
                inter.add(a);
            
        }
        int result[] = new int[inter.size()];
        int i = 0;
        for(int s:inter)
            result[i++] = s;
        return result;
    }

思路简单,代码啰嗦,用python三行搞定

 def intersection(self, nums1, nums2):
        a = set(nums1)
        b = set(nums2)
        return list(a & b);
原文地址:https://www.cnblogs.com/wxshi/p/7605230.html