- Notifications
You must be signed in to change notification settings - Fork24
Open
Labels
Description
借用 Map
- 先明确题意,题目让我们求交集,也就是两个数组共有的元素
- 借用 Map,遍历 nums1,将 nums1 中的元素作为 key,value 都设置为 true 填充 Map
- 遍历 nums2,如果在 map 中出现过,也就是说在 nums1 中出现过,就是他们共有的元素,push 进 res,从 map 中删除。
- 最后返回 res 即可
constintersection=function(nums1,nums2){constmap=newMap()constres=[]nums1.forEach(n=>{map.set(n,true)})nums2.forEach(n=>{if(map.get(n)){res.push(n)map.delete(n)}})returnres}
- 时间复杂度: O(m + n)
- 空间复杂度: O(m)