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;
    }
}复制代码

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

查看所有标签

猜你喜欢:

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

The Zen of CSS Design

The Zen of CSS Design

Dave Shea、Molly E. Holzschlag / Peachpit Press / 2005-2-27 / USD 44.99

Proving once and for all that standards-compliant design does not equal dull design, this inspiring tome uses examples from the landmark CSS Zen Garden site as the foundation for discussions on how to......一起来看看 《The Zen of CSS Design》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

随机密码生成器
随机密码生成器

多种字符组合密码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换