0
点赞
收藏
分享

微信扫一扫

349. Intersection of Two Arrays

晒大太阳了 2022-08-23 阅读 31



Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = ​​[1, 2, 2, 1]​​, nums2 = ​​[2, 2]​​​, return ​​[2]​​.

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""

small = []
big = []
if len(nums1) < len(nums2):
small = nums1
big = nums2
else:
small = nums2
big = nums1

r = []
for i in small:
if i in big and i not in r:
r.append(i)
return

349. Intersection of Two Arrays_java


虽然AC了,但是用时太长了,需要优化一下

优化的思路是使用set,去重

class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
s = set(nums2)# 去重
b = set(nums1)

r = []
for i in s:
if i in b and i not in r:
r.append(i)
b.remove(i)
return

349. Intersection of Two Arrays_java_02


举报

相关推荐

0 条评论