Leetcode.349两个数组的交集

Leetcode.349两个数组的交集

题目难度:简单
题目:原题链接
给定两个数组,编写一个函数来计算它们的交集。

思路

  1. 建立两个集合,首先将nums1和nums2元素放到建立的集合里面;
  2. 为什么要建立集合呢?因为集合中的元素是不会重复的,所以在比较过程就不用重复比较多次啦;
  3. 判断集合长度,我们只用遍历较短的集合就可以啦;
  4. 新创建一个集合用于存放交的元素即交集;
  5. 使用了set.contains函数,判断是否在其中,这道题如果用python写会更加简洁一些;
  6. 最后要放在数组输出;
  7. 和官方代码写的类似,不过遍历还是学习了官方的方法
    给出官方代码
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<Integer>();
        Set<Integer> set2 = new HashSet<Integer>();
        for (int num : nums1) {
            set1.add(num);
        }
        for (int num : nums2) {
            set2.add(num);
        }
        return getIntersection(set1, set2);
    }

    public int[] getIntersection(Set<Integer> set1, Set<Integer> set2) {
        if (set1.size() > set2.size()) {
            return getIntersection(set2, set1);
        }
        Set<Integer> intersectionSet = new HashSet<Integer>();
        for (int num : set1) {
            if (set2.contains(num)) {
                intersectionSet.add(num);
            }
        }
        int[] intersection = new int[intersectionSet.size()];
        int index = 0;
        for (int num : intersectionSet) {
            intersection[index++] = num;
        }
        return intersection;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值