首页 > 其他 > 详细

Intersection of Two Arrays

时间:2016-06-02 23:16:26      阅读:290      评论:0      收藏:0      [点我收藏+]

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.

一道easy的题目,感觉诸多提示如unique,in any order。感觉使用set是一个非常好的选择,也是先将数组1放入set1中,数组2放入set2中,然后对这两个集合求并,就可以得到最终的结果,代码如下:

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        map1 = set(nums1)
        map2 = set(nums2)
        return list(map1 & map2)

总体的复杂度为O(n), python的set是基于字典的操作,所以相关的复杂度和字典一样。

Intersection of Two Arrays

原文:http://www.cnblogs.com/sherylwang/p/5554617.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!