码迷,mamicode.com
首页 > 其他好文 > 详细

349. Intersection of Two Arrays (Easy)

时间:2017-09-08 18:24:36      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:type   style   返回   ret   color   function   turn   python   sel   

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

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2].

Note:

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

题意:保证列表中每个元素都是唯一的;利用python中列表求交集的方法;

思路:

1.遍历nums1,如果某个元素同时也存在于nums2中,则返回,并利用set()去重;

2.把列表转换为集合,利用集合操作符求出交集,然后再转换回列表类型;

# 遍历
class Solution():
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        list_a = [n for n in set(nums1) if n in nums2]
        return list_a
# 利用set数据结构的与运算
class Solution():
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
    
        return list(set(nums1) & set(nums2)) 

 

349. Intersection of Two Arrays (Easy)

标签:type   style   返回   ret   color   function   turn   python   sel   

原文地址:http://www.cnblogs.com/yancea/p/7495318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!