mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-01-27 19:58:06 +01:00
Add solution using hash map
This commit is contained in:
parent
e56c0b2fa2
commit
e70ba583a2
1 changed files with 18 additions and 0 deletions
|
@ -9,8 +9,26 @@
|
||||||
# @param {Integer[]} nums
|
# @param {Integer[]} nums
|
||||||
# @return {Integer}
|
# @return {Integer}
|
||||||
|
|
||||||
|
#
|
||||||
|
# Approach 1: Hash map
|
||||||
|
#
|
||||||
|
# Time Complexity: O(n)
|
||||||
|
#
|
||||||
def single_number(nums)
|
def single_number(nums)
|
||||||
|
result_hash = {}
|
||||||
|
nums.each do |num|
|
||||||
|
if result_hash[num]
|
||||||
|
result_hash[num] +=1
|
||||||
|
else
|
||||||
|
result_hash[num] = 1
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
result_hash.each do |k, v|
|
||||||
|
return k if v == 1
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
nums = [2, 2, 1]
|
nums = [2, 2, 1]
|
||||||
puts(single_number(nums))
|
puts(single_number(nums))
|
||||||
# Output: 1
|
# Output: 1
|
||||||
|
|
Loading…
Add table
Reference in a new issue