mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-01-29 20:34:27 +01:00
Add hash approach
This commit is contained in:
parent
da897fe6ad
commit
8e3ec5a9dd
1 changed files with 33 additions and 0 deletions
|
@ -37,6 +37,39 @@ puts(num_identical_pairs(nums))
|
|||
# Output: 6
|
||||
# Explanation: Each pair in the array are good.
|
||||
|
||||
nums = [1, 2, 3]
|
||||
puts(num_identical_pairs(nums))
|
||||
# Output: 0
|
||||
|
||||
#
|
||||
# Approach 2: Hash
|
||||
#
|
||||
def num_identical_pairs(nums)
|
||||
hash = Hash.new(0)
|
||||
|
||||
nums.each do |num|
|
||||
hash[num] = hash[num] + 1
|
||||
end
|
||||
|
||||
counter = 0
|
||||
# Count how many times each number appears.
|
||||
# If a number appears n times, then n * (n – 1) / 2 good pairs
|
||||
# can be made with this number.
|
||||
hash.values.each do |val|
|
||||
counter += (val * (val - 1) / 2)
|
||||
end
|
||||
|
||||
counter
|
||||
end
|
||||
|
||||
nums = [1, 2, 3, 1, 1, 3]
|
||||
puts(num_identical_pairs(nums))
|
||||
# Output: 4
|
||||
|
||||
nums = [1, 1, 1, 1]
|
||||
puts(num_identical_pairs(nums))
|
||||
# Output: 6
|
||||
|
||||
nums = [1, 2, 3]
|
||||
puts(num_identical_pairs(nums))
|
||||
# Output: 0
|
Loading…
Add table
Reference in a new issue