您的位置:首页 > 编程语言 > Python开发

350. Intersection of Two Arrays II [easy] (Python)

2016-05-25 10:15 579 查看

题目链接

https://leetcode.com/problems/intersection-of-two-arrays-ii/

题目原文

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

Example:

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

Note:

Each element in the result should appear as many times as it shows in both arrays.

The result can be in any order.

题目翻译

给定两个数组,写一个函数计算它们的交。

比如:给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2],返回 [2, 2]。

注意:结果中每个元素出现的次数应该与它同时出现在两个数组中的次数相同;结果的顺序没有要求。

思路方法

思路一

暴力查找法,遍历第一个列表的每个元素,并在第二个列表中查找该元素是否出现,若出现且结果集中没有,则加入到结果集中。

代码

class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
res = []
for k in nums1:
index = -1
for j in xrange(0, len(nums2)):
if nums2[j] == k:
index = j
break
if index != -1:
res.append(k)
del nums2[index]

return res


思路二

类似思路一,为了提高效率,先对第二个列表先排序,每次检查元素是否出现时用二分搜索。

代码

class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
res = []
nums2.sort()
for k in nums1:
flag, j = self.binarySearch(nums2, k)
if flag:
res.append(k)
del nums2[j]
return res

def binarySearch(self, nums, num):
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) / 2
if nums[mid] == num:
return True, mid
if nums[mid] < num:
left = mid + 1
else:
right = mid - 1
return False, 0


思路三

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

代码

class Solution(object):
def intersect(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] -= 1

return res


思路四

类似思路三的思想,不过是将两个数组都统计成dict,再计算交集。这时可以利用Python的collections模块的Counter来帮助统计,实现一行代码AC。

代码

class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list((collections.Counter(nums1) & collections.Counter(nums2)).elements())


思路五

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

代码

class Solution(object):
def intersect(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]:
res.append(nums1[i])
i += 1
j += 1
elif nums1[i] < nums2[j]:
i += 1
elif nums1[i] > nums2[j]:
j += 1

return res


PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!

转载请注明:/article/11857835.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: