題目:原題鏈接(簡單)
解法 | 時間複雜度 | 空間複雜度 | 執行用時 |
---|---|---|---|
Ans 1 (Python) | – | – | 56ms (85.78%) |
Ans 2 (Python) | O(n^2) | O(n) | 84ms (28.84%) |
Ans 3 (Python) | O(m+n) | O(m+n) | 88ms (23.15%) |
LeetCode的Python執行用時隨緣,只要時間複雜度沒有明顯差異,執行用時一般都在同一個量級,僅作參考意義。
解法一(Pythonic):
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
解法二(迭代):
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
ans = []
for n in nums2:
if n in nums1 and n not in ans:
ans.append(n)
return ans
解法三(兩個set):
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1 = set(nums1)
nums2 = set(nums2)
if len(nums1) < len(nums2):
return [x for x in nums2 if x in nums1]
else:
return [x for x in nums1 if x in nums2]