leetcode 349. 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.

两种思路,一种是map,一种是排序归并的思想:

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        #return list(set(nums1) & set(nums2))
        nums1.sort()
        nums2.sort()
        i = j = 0
        arr = set()
        while i<len(nums1) and j<len(nums2):
            if nums1[i] == nums2[j]:
                arr.add(nums1[i])
                i += 1
                j += 1
            elif nums1[i] > nums2[j]:
                j += 1
            else:
                i += 1
        return list(arr)

 

posted @ 2018-03-25 12:20  bonelee  阅读(149)  评论(0编辑  收藏  举报