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].

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是基于字典的操作,所以相关的复杂度和字典一样。

posted on 2016-06-02 22:19  Sheryl Wang  阅读(145)  评论(0编辑  收藏  举报

导航