LeetCode每日一题:两个数组的交集(No.349)

栏目: 编程工具 · 发布时间: 6年前

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

输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
复制代码

思考:

先将两个数组中的元素放入两个Set中过滤重复元素,在遍历两个Set查找相同元素即可。
复制代码

实现:

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        List<Integer> resultList = new ArrayList<>();
        Set<Integer> numSet1 = new HashSet<>();
        Set<Integer> numSet2 = new HashSet<>();
        for (int count = 0; count < nums1.length; count++) {
            numSet1.add(nums1[count]);
        }
        for (int count = 0; count < nums2.length; count++) {
            numSet2.add(nums2[count]);
        }
        for (Integer num : numSet1) {
            if (numSet2.contains(num)) {
                resultList.add(num);
            }
        }
        int[] result = new int[resultList.size()];
        for (int count = 0; count < result.length; count++) {
            result[count] = resultList.get(count);
        }
        return result;
    }
}复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Viral Loop

Viral Loop

Adam L. Penenberg / Tantor Media / 2009-10-27 / USD 34.99

From Google to Facebook, a respected journalist delves into how a "viral loop" can make an online business a success.一起来看看 《Viral Loop》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

html转js在线工具
html转js在线工具

html转js在线工具