349. Intersection of Two Arrays

    xiaoxiao2021-03-25  131

    Given two arrays, write afunction to compute their intersection.

    Example:

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

    Note:

    Each element in the resultmust be unique.

    The result can be in anyorder.

        翻译:就是有两个整形数组,求数组的交集,返回集合中的数不重复。这题我首先想到的额是用map集合,它里面的数不可重复。但是最后写完了之后,发现返回值一直不对。这个需要注意的。代码如下:

    public class Solution {

        public int[] intersection(int[] nums1,int[] nums2) {

                Map<Integer,Integer> map1=newHashMap();

                    Map<Integer,Integer> map2=newHashMap();

                   

                    for(int i=0;i<nums1.length;i++){

                              map1.put(nums1[i], i);

                    }

                    for(int i=0;i<nums2.length;i++){

                 if(map1.containsKey(nums2[i])){

                            map2.put(nums2[i], i);

                        }

                    }

                    int []a =new int[map2.size()];

                    int count=0;

                    for(int i:map2.keySet()){

                       if(map1.containsKey(i)){

                               a[count++]=i;

                         }

                    }

                    return a;

             

        }

    }

        int []a =new int[map2.size()];在声明数组的空间之前应该需要知道有多少个交集了,不应该在之后进行比较,这点需要注意一下。还有就是数组申明要初始化的。这题也可以用Set集合,以前一直用的List,Set忽视了,其实用它比较好。set底层实现方式为RB树(即红黑树)。

    转载请注明原文地址: https://ju.6miu.com/read-9772.html

    最新回复(0)