首页 > 其他 > 详细

349-两个阵列的交集

时间:2019-04-14 18:01:00      阅读:85      评论:0      收藏:0      [点我收藏+]

给定两个数组,编写一个函数来计算它们的交集。

例1: 输入: nums1 = [1,2,2,1],nums2 = [2,2]  输出:[2] 

例2: 输入: nums1 = [4,9,5],nums2 = [9,4,9,8,4]  输出:[9,4]

注意: 结果中的每个元素都必须是唯一的。 结果可以是任何顺序。

 

解法1:
使用HashSet和迭代器:
  public static int[] intersection(int[] nums1, int[] nums2) {
        Set hashset1=new HashSet();
        Set hashset2=new HashSet();
        int i=0,j=0,k=0;
        while (i<nums1.length||j<nums2.length)
        {
            if (i<nums1.length)
            {
                hashset1.add(nums1[i]);
                i++;
            }
            if (j<nums2.length)
            {
                hashset2.add(nums2[j]);
                j++;
            }
        }
        int A[]=new int[hashset1.size()+hashset2.size()];
        Iterator iterator1=hashset1.iterator();
        while (iterator1.hasNext())
        {
            int a= (int) iterator1.next();
            if (hashset2.contains(a))
            {
                A[k]=a;
                k++;
            }
        }
        int B[]=new int[k];
        for (int m=0;m<k;m++)
        {
           B[m]=A[m];
        }
        return B;
    }

改进后:
public static int[] intersection(int[] nums1, int[] nums2) {
        Set hashset1=new HashSet();
        Set hashset2=new HashSet();

        for (int i=0;i<nums1.length;i++)
        {
            hashset1.add(nums1[i]);
        }
        for (int j=0;j<nums2.length;j++)
        {
            if (hashset1.contains(nums2[j]))
            {
                hashset2.add(nums2[j]);
            }
        }
        int m=0;
        int A[]=new int[hashset2.size()];
        Iterator iterator=hashset2.iterator();
        while (iterator.hasNext())
        {
            int a= (int) iterator.next();
            A[m]=a;
            m++;
        }
        return A;
    }

 

349-两个阵列的交集

原文:https://www.cnblogs.com/dloading/p/10706100.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!