⚠️ 舊文提醒:本文發佈於約 4 年前,部分內容或指令可能已過時,請斟酌參考。
題目在此 350. Intersection of Two Arrays II
請找出兩個數列之間重複的元素
解題思維
如果沒解過 349. Intersection of Two Arrays,可以先看一下這題
再使用 Two Pointers 大法慢慢往下掃之前,記得需要先 Sorting
這個方法就可以在 O(N) 內把問題空間掃描一下
完成!
程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: if not nums1 or not nums2: return [] nums1.sort() nums2.sort() size1 = len(nums1) size2 = len(nums2) index1 = index2 = 0 result = [] while index1 < size1 and index2 < size2: if nums1[index1] < nums2[index2]: index1 += 1 continue elif nums1[index1] > nums2[index2]: index2 += 1 continue result.append(nums1[index1]) index1 += 1 index2 += 1 return result
|
也許你也會想看看