Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:
Givennums1=[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.
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))
#use dict/hashmap to record all nums appeared in the first list, and then check if there are nums in the second list have appeared in the map.
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
hashmap = {}
result = []
for i in range(len(nums1)):
hashmap[nums1[i]] = i
for num2 in nums2:
if num2 in hashmap and num2 not in result:
result.append(num2)
return result
两个指针来做,先给两个数组排序,然后用两个指针分别指向两个数组的开头,然后比较两个数组的大小,把小的数字的指针向后移,如果两个指针指的数字相等,那么看结果res是否为空,如果为空或者是最后一个数字和当前数字不等的话,将该数字加入结果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
二刷:
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result =[]
hashmap = collections.Counter(nums1)
for num in nums2:
if num in hashmap and hashmap[num] > 0:
result.append(num)
hashmap[num] = -1
return result
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result = []
hash=collections.Counter(nums1)
for num2 in nums2:
if num2 in hash and num2 not in result:
result.append(num2)
return result
Last updated
Was this helpful?