mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-26 21:58:56 +01:00
Add hash solution
This commit is contained in:
parent
2c11993806
commit
7b20bca2f8
1 changed files with 32 additions and 0 deletions
|
@ -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)
|
||||
|
|
Loading…
Reference in a new issue