方法一:排序 + 双指针
class Solution(object):def intersect(self, nums1, nums2):""":type nums1: List[int]:type nums2: List[int]:rtype: List[int]""" nums1.sort() nums2.sort()res &#61; []n1, n2 &#61; len(nums1), len(nums2)i, j &#61; 0, 0while i < n1 and j < n2:if nums1[i] &#61;&#61; nums2[j]:res.append(nums1[i])i &#43;&#61; 1j &#43;&#61; 1elif nums1[i] < nums2[j]:i &#43;&#61; 1else:j &#43;&#61; 1return res
方法二&#xff1a;哈希表
import collections
class Solution(object):def intersect(self, nums1, nums2):""":type nums1: List[int]:type nums2: List[int]:rtype: List[int]""" dic1 &#61; collections.Counter(nums1)dic2 &#61; collections.Counter(nums2)dic &#61; dic1 & dic2res &#61; []for i, num in enumerate(dic):while dic[num] > 0:res.append(num)dic[num] -&#61; 1return res