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