资讯专栏INFORMATION COLUMN

LeetCode 349. Intersection of Two Arrays

RyanQ / 481人阅读

摘要:描述给定两个数组,编写一个函数来计算它们的交集。示例输入输出示例输入输出说明输出结果中的每个元素一定是唯一的。我们可以不考虑输出结果的顺序。思路内置集合可以完成交运算,然后再转换为即可。何睿何睿内置集合运算源代码文件在这里。

Description

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Note:

Each element in the result must be unique.
The result can be in any order.

描述

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

示例 1:

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

输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
说明:

输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。

思路

python 内置 set 集合可以完成交运算,然后再转换为 List 即可。

# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-04-09 16:11:29
# @Last Modified by:   何睿
# @Last Modified time: 2019-04-09 16:15:56


class Solution:
    def intersection(self, nums1: [int], nums2: [int]) -> [int]:
        # python 内置集合运算
        return list(set(nums1) & set(nums2))

源代码文件在 这里 。
©本文首发于 何睿的博客 ,欢迎转载,转载需保留 文章来源 ,作者信息和本声明.

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/43553.html

相关文章

  • leetcode349. Intersection of Two Arrays

    摘要:题目要求找出两个无序数组中重合的值。先将两个数组分别排序,排序完成之后再用两个指针分别比较两个数组的值。如果两个指针指向的值相同,则向结果集中添加该元素并且同时将两个指针向前推进。答案是为其中一个数组通过建立索引的方式排序。 题目要求 Given two arrays, write a function to compute their intersection. Example: ...

    only_do 评论0 收藏0
  • Leetcode PHP题解--D72 349. Intersection of Two Array

    摘要:题目链接题目分析返回给定两个数组的交集。思路这既然不是自己实现的话,直接用就完事了。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D72 349. Intersection of Two Arrays 题目链接 349. Intersection of Two Arrays 题目分析 返回给定两个数组的交集。 思路 这既然不是自己实现的话,直接用array_intersect就完事...

    sixleaves 评论0 收藏0
  • LeetCode 攻略 - 2019 年 7 月下半月汇总(100 题攻略)

    摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...

    tain335 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • [LintCode/LeetCode] Intersection of Two Arrays I &

    摘要:先想到的是,其实也可以,只是需要在遍历的时候,添加到数组中的数要掉,略微麻烦了一点。在里跑的时候,也要快一点。另一种类似做法的就快的多了。如果是找出所有包括重复的截距呢 Problem Given two arrays, write a function to compute their intersection. Notice Each element in the result m...

    enda 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<