您的位置:首页 > 其它

20170403-leetcode-349/50-Intersection of Two Arrays.py

2017-04-03 10:44 676 查看
两个同类型的题:349/350. 349:1、2;350:3,4

1.Description

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.


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.

解读

求两个数组的交集

2.Solution

变为set,求交集,再变为list

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


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


Follow up:

What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?


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.

Follow up:

What if the given array is already sorted? How would you optimize your algorithm?

What if nums1’s size is small compared to nums2’s size? Which algorithm is better?

What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

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

解读

这次要求不去重复,有多少就找多少

4.Solution

方法:仍然先求集合的并集,找到公共元素,然后遍历这些元素找到他们在两个数组中的个数,取较小的值,添加到结果中

def intersect(self, nums1, nums2):
dict1 = collections.Counter(nums1)
dict2 = collections.Counter(nums2
result=[]
for num in set(nums1) & set(nums2):
result += [num] * (min(dict1[num], dict2[num]))
return result


mark:collection.Counter(list)的返回值是字典类型
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: