mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-26 21:58:56 +01:00
Add solution using Ruby .count()
This commit is contained in:
parent
e70ba583a2
commit
e8ded18897
1 changed files with 22 additions and 1 deletions
|
@ -23,12 +23,33 @@ def single_number(nums)
|
|||
result_hash[num] = 1
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
result_hash.each do |k, v|
|
||||
return k if v == 1
|
||||
end
|
||||
end
|
||||
|
||||
nums = [2, 2, 1]
|
||||
puts(single_number(nums))
|
||||
# Output: 1
|
||||
nums = [4, 1, 2, 1, 2]
|
||||
puts(single_number(nums))
|
||||
# Output: 4
|
||||
nums = [1]
|
||||
puts(single_number(nums))
|
||||
# Output: 1
|
||||
|
||||
#
|
||||
# Approach 2: Use Ruby .count()
|
||||
#
|
||||
# Time Complexity: O(1)
|
||||
#
|
||||
def single_number(nums)
|
||||
nums.find do |num|
|
||||
nums.count(num) == 1
|
||||
end
|
||||
end
|
||||
|
||||
nums = [2, 2, 1]
|
||||
puts(single_number(nums))
|
||||
# Output: 1
|
||||
|
|
Loading…
Reference in a new issue