LeetCode--350. Intersection of Two Arrays II(两个数组的交集)Python
2018-01-18 13:33
676 查看
题目:
给定两个数组,返回这两个数组的交集。
解题思路:
使用哈希表用来存储第一个数组中的内容。再遍历第二个数组,看该数组的数字是否在哈希表中,在则将该数字加入输出的列表中。
代码(Python):
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
output = []
Dict = {}
for i in nums1:
if i in Dict:
Dict[i] = Dict[i]+1
else:
Dict[i] = 1
for i in nums2:
if i in Dict:
if Dict[i]>=1:
Dict[i] = Dict[i]-1
output.append(i)
continue
else:
continue
else:
continue
return output
给定两个数组,返回这两个数组的交集。
解题思路:
使用哈希表用来存储第一个数组中的内容。再遍历第二个数组,看该数组的数字是否在哈希表中,在则将该数字加入输出的列表中。
代码(Python):
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
output = []
Dict = {}
for i in nums1:
if i in Dict:
Dict[i] = Dict[i]+1
else:
Dict[i] = 1
for i in nums2:
if i in Dict:
if Dict[i]>=1:
Dict[i] = Dict[i]-1
output.append(i)
continue
else:
continue
else:
continue
return output
相关文章推荐
- Leetcode:350. Intersection of Two Arrays II 求两个数组的交集
- [easy]【leetcode】【java】 Intersection of Two Arrays II 两个数组的交集
- Leetcode 350. Intersection of Two Arrays II 两个数组的交集 II
- leetcode-350 Intersection of Two Arrays II 求两个数组的交集 面试见到了吗?
- leetcode 350. Intersection of Two Arrays II 两个数组的交集
- [LeetCode] Intersection of Two Arrays II 两个数组的交集II
- [LeetCode]350. Intersection of Two Arrays II(求两个数组交集 II)
- [LeetCode] Intersection of Two Arrays 两个数组的交集
- [LeetCode] 350. Intersection of Two Arrays II 两个数组相交II
- Leetcode 350. Intersection of Two Arrays II 数组交集2 解题报告
- Leetcode :Intersection of Two Arrays 两个数组的交集
- LeetCode 350. Intersection of Two Arrays II (两个数组的相交之二)
- LeetCode 350. Intersection of Two Arrays II(数组交集)
- Intersection of Two Arrays II两个数组交集(重要!)
- 350. Intersection of Two Arrays II (求两个数组的交集,包含重复元素)
- [LeetCode] Intersection of Two Arrays II 两个数组相交之二
- LeetCode 4 Median of Two Sorted Arrays (两个数组的mid值)
- leetcode04 Median of Two Sorted Arrays 两个已排序数组的中位数
- [LeetCode] Median of Two Sorted Arrays 两个有序数组的中位数
- leetcode 4 : Median of Two Sorted Arrays 找出两个数组的中位数