349. Intersection of Two Arrays [easy] (Python)

题目链接

https://leetcode.com/problems/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.

题目翻译

给定两个数组,写一个函数求它们的交。
比如:给定数组nums1 = [1, 2, 2, 1], nums2 = [2, 2],应该返回[2]。
注意:结果中每个元素是唯一的;结果的顺序没有要求。

思路方法

思路一

这个问题本质就是求集合的交集,出于用Python的原因,先给出用set操作求解的方法。当然,这个做法掩盖了太多细节,并不适合学习算法,仅供参考。

代码

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))

思路二

暴力查找法,遍历第一个列表的每个元素,并在第二个列表中查找该元素是否出现,若出现且结果集中没有,则加入到结果集中。
另外,如果想提高效率,可以对第二个列表先排序,每次检查元素是否出现时用二分搜索。

代码

class Solution(object):
    def intersection(self, nums1, nums2):
        """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """
        res = []
        for i in nums1:
            if i not in res and i in nums2:
                res.append(i)

        return res

思路三

用字典统计第一个列表都出现了哪些数,然后顺序遍历第二个列表,发现同时出现的数则加入到结果列表中。

代码

class Solution(object):
    def intersection(self, nums1, nums2):
        """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """
        res = []
        map = {}
        for i in nums1:
            map[i] = map[i]+1 if i in map else 1
        for j in nums2:
            if j in map and map[j] > 0:
                res.append(j)
                map[j] = 0

        return res

思路四

先将两个数组排序,再维持两个指针分别扫描两个数组,寻找共同的元素。

代码

class Solution(object):
    def intersection(self, nums1, nums2):
        """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """
        res = []
        nums1.sort()
        nums2.sort()
        i = j = 0
        while (i < len(nums1) and j < len(nums2)):
            if nums1[i] > nums2[j]:
                j += 1
            elif nums1[i] < nums2[j]:
                i += 1
            else:
                if not (len(res) and nums1[i] == res[len(res)-1]):
                    res.append(nums1[i])
                i += 1
                j += 1

        return res

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51452615

    原文作者:coder_orz
    原文地址: https://blog.csdn.net/coder_orz/article/details/51452615
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞