Intersection of Two Arrays II (Leetcode 350)
Problem Link: https://leetcode.com/problems/intersection-of-two-arrays-ii/
Using Hashing:
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
ans=[]
d1={}
d2={}
for i in nums1:
if(i not in d1):
d1[i]=1
else:
d1[i]+=1
for i in nums2:
if(i in d1):
ans.append(i)
if(d1[i]==1):
del d1[i]
else:
d1[i]-=1
return ans
Using Sorting:
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
ans=[]
nums1.sort()
nums2.sort()
i=0
j=0
while(i<len(nums1) and j<len(nums2)):
if(nums1[i]<nums2[j]):
i+=1
elif(nums2[j]<nums1[i]):
j+=1
else:
ans.append(nums1[i])
i+=1
j+=1
return ans
Last updated