350 intersection of two arrays ii
350. Intersection of Two Arrays II
题目:
https://leetcode.com/problems/intersection-of-two-arrays-ii/
难度:
Easy
sort之后用了双指针来走和看
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort()
nums2.sort()
l1 = len(nums1)
l2 = len(nums2)
p1 = 0
p2 = 0
res = []
while p1 < l1 and p2 < l2:
if nums1[p1] < nums2[p2]:
p1 += 1
elif nums1[p1] > nums2[p2]:
p2 += 1
else:
res.append(nums1[p1])
p1 += 1
p2 += 1
return res
两行版本
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
a, b = map(collections.Counter, (nums1, nums2))
return list((a & b).elements())