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 r
虽然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 r