TheAlgorithms-Ruby/data_structures/arrays/single_number.rb

62 lines
1 KiB
Ruby
Raw Normal View History

2021-03-19 16:26:23 -07:00
# Challenge name: Single Number
#
# Given a non-empty array of integers nums, every element appears twice
# except for one. Find that single one.
#
# Follow up: Could you implement a solution with a linear runtime
# complexity and without using extra memory?
#
# @param {Integer[]} nums
# @return {Integer}
2021-09-03 13:24:58 -07:00
#
2021-03-22 08:07:14 -07:00
# Approach 1: Hash map
#
# Time Complexity: O(n)
#
2021-03-19 16:26:23 -07:00
def single_number(nums)
2021-03-22 08:07:14 -07:00
result_hash = {}
nums.each do |num|
if result_hash[num]
2021-09-03 13:24:58 -07:00
result_hash[num] += 1
2021-03-22 08:07:14 -07:00
else
result_hash[num] = 1
end
end
2021-03-22 08:53:26 -07:00
2021-03-22 08:07:14 -07:00
result_hash.each do |k, v|
return k if v == 1
end
2021-03-19 16:26:23 -07:00
end
2021-03-22 08:07:14 -07:00
2021-03-22 08:53:26 -07:00
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()
#
2021-03-23 08:05:54 -07:00
# Time Complexity: O(n^2)
2021-03-22 08:53:26 -07:00
#
def single_number(nums)
nums.find do |num|
nums.count(num) == 1
end
end
2021-03-19 16:26:23 -07:00
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))
2021-09-03 13:24:58 -07:00
# Output: 1