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中
二刷:
Last updated
Was this helpful?