TheAlgorithms-Ruby/data_structures/arrays/single_number.rb

62 lines
1 KiB
Ruby
Raw Permalink Normal View History

2021-03-20 00:26:23 +01: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 22:24:58 +02:00
#
2021-03-22 16:07:14 +01:00
# Approach 1: Hash map
#
# Time Complexity: O(n)
#
2021-03-20 00:26:23 +01:00
def single_number(nums)
2021-03-22 16:07:14 +01:00
result_hash = {}
nums.each do |num|
if result_hash[num]
2021-09-03 22:24:58 +02:00
result_hash[num] += 1
2021-03-22 16:07:14 +01:00
else
result_hash[num] = 1
end
end
2021-03-22 16:53:26 +01:00
2021-03-22 16:07:14 +01:00
result_hash.each do |k, v|
return k if v == 1
end
2021-03-20 00:26:23 +01:00
end
2021-03-22 16:07:14 +01:00
2021-03-22 16:53:26 +01: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 16:05:54 +01:00
# Time Complexity: O(n^2)
2021-03-22 16:53:26 +01:00
#
def single_number(nums)
nums.find do |num|
nums.count(num) == 1
end
end
2021-03-20 00:26:23 +01: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 22:24:58 +02:00
# Output: 1