Leetcode-Intersection of Two Arrays-Python

来源:互联网 发布:按键精灵可以编vb 编辑:程序博客网 时间:2024/05/22 12:28

Intersection of Two Arrays

查找两个数组的共有元素。
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Description

解题思路
本来是想做关于排序的题目的,然后这道题的标签中就是含sort的,但我觉得用集合的方式会更简明些。

class Solution(object):    def intersection(self, nums1, nums2):        """        :type nums1: List[int]        :type nums2: List[int]        :rtype: List[int]        """        set1 = set(nums1)        set2 = set(nums2)        return list(set1.intersection(set2))                       

tip
set求交集函数返回的是set,因此需要通过list进行转换。

原创粉丝点击