mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-27 21:58:57 +01:00
Hash table approach
This commit is contained in:
parent
47a8216712
commit
13a2fe09b5
1 changed files with 30 additions and 0 deletions
|
@ -55,4 +55,34 @@ Benchmark.bmbm do |x|
|
|||
x.report('execute algorithm') do
|
||||
print find_duplicates_2(long_array)
|
||||
end
|
||||
end
|
||||
|
||||
def find_duplicates_3(array)
|
||||
result_hash = {}
|
||||
result_array = []
|
||||
# loop through array and build a hash with counters
|
||||
# where the key is the array element and the counter is the value
|
||||
# increase counter when duplicate is found
|
||||
array.each do |num|
|
||||
if result_hash[num].nil?
|
||||
result_hash[num] = 1
|
||||
else
|
||||
result_hash[num] += 1
|
||||
end
|
||||
end
|
||||
# loop through hash and look for values > 1
|
||||
result_hash.each do |k, v|
|
||||
if v > 1
|
||||
result_array.push(k)
|
||||
end
|
||||
end
|
||||
# return keys
|
||||
result_array
|
||||
end
|
||||
|
||||
require 'benchmark'
|
||||
Benchmark.bmbm do |x|
|
||||
x.report('execute algorithm') do
|
||||
print find_duplicates_3(array)
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue