Add hash solution

This commit is contained in:
Jessica Kwok 2021-04-16 16:21:49 -07:00
parent 2c11993806
commit 7b20bca2f8

View file

@ -38,6 +38,38 @@ nums2 = [2, 2]
puts intersect(nums1, nums2)
# => [2,2]
nums1 = [4, 9, 5]
nums2 = [9, 4, 9, 8, 4]
puts intersect(nums1, nums2)
# => [4,9]
#
# Approach 2: Hash
#
# Time Complexity: O(n)
#
def intersect(arr1, arr2)
result = []
hash = Hash.new(0)
arr2.each {|num| hash[num] += 1 }
arr1.each do |num|
if hash.has_key?(num)
result << num if hash[num] >= 1
hash[num] -= 1
end
end
result
end
nums1 = [1, 2, 2, 1]
nums2 = [2, 2]
puts intersect(nums1, nums2)
# => [2,2]
nums1 = [4, 9, 5]
nums2 = [9, 4, 9, 8, 4]
puts intersect(nums1, nums2)