原題是:
Given two arrays, write a function to compute their intersection.
***: 349.是該題的簡單版本,區別是結果不需要返回重復的結果。
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
思路:
這個題有兩個標準解法:
1.是我代碼所寫的two pointer方法。先將兩個數組排序,然后兩指針分別比較對應位置。誰大了,挪動另一個指針。相等則把該元素插入結果中。
2.用hash table 存第一個數組的元素對應元素出現的個數。再遍歷第二個數組,對于hashtable中已有的Key,填入結果,并將value值減去1。
對follow-up:
3.如果內存不夠,那只能用哈希的方法,第二個數組分批載入。而第一個方法,由于需要排序,無法分批載入數組。
代碼是:
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
i,j = 0,0
num1 = sorted(nums1)
num2 = sorted(nums2)
res = []
while i < len(num1) and j < len(num2):
if num1[i] < num2[j]:
i += 1
elif num1[i] > num2[j]:
j += 1
else:
res.append(num1[i])
i += 1
j += 1
return res