描述
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
解析
根据题意,先把两个列表排序,然后设置两个指针 i 和 j 遍历两个数组,判断是否有相同的元素,最后把结果都放入列表返回即可。时间复杂度为 O(NlogN),空间复杂度为 O(N)。另外一种方法是用字典统计个数,然后取同在两个数组中的字符的最小出现次数,将结果放入列表总返回即可。时间复杂度为 O(N),空间复杂度为 O(N).
解答
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort()
nums2.sort()
i,j=0,0
result = []
while i<len(nums1) and j<len(nums2):
if nums1[i] == nums2[j]:
result.append(nums1[i])
i+=1
j+=1
elif nums1[i]>nums2[j]:
j+=1
elif nums1[i]<nums2[j]:
i+=1
return result
运行结果
Runtime: 36 ms, faster than 69.70% of Python online submissions for Intersection of Two Arrays II.
Memory Usage: 11.9 MB, less than 31.89% of Python online submissions for Intersection of Two Arrays II.
每日格言:逆境是达到真理的一条通路。
请作者吃饺子 支付宝