From e70ba583a280f0dd62f16b16496035a07fcf91a4 Mon Sep 17 00:00:00 2001 From: Jessica Kwok Date: Mon, 22 Mar 2021 08:07:14 -0700 Subject: [PATCH] Add solution using hash map --- data_structures/arrays/single_number.rb | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/data_structures/arrays/single_number.rb b/data_structures/arrays/single_number.rb index 5c68747..f639857 100644 --- a/data_structures/arrays/single_number.rb +++ b/data_structures/arrays/single_number.rb @@ -9,8 +9,26 @@ # @param {Integer[]} nums # @return {Integer} +# +# Approach 1: Hash map +# +# Time Complexity: O(n) +# 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 + nums = [2, 2, 1] puts(single_number(nums)) # Output: 1