Merge branch 'jk-shuffle-array' of https://github.com/jsca-kwok/Ruby into jk-shuffle-array

This commit is contained in:
Jessica Kwok 2021-03-29 10:22:23 -07:00
commit d68ae157cd
2 changed files with 62 additions and 0 deletions

View file

@ -14,6 +14,7 @@
* [Get Products Of All Other Elements](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/get_products_of_all_other_elements.rb)
* [Remove Elements](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/remove_elements.rb)
* [Shuffle Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/shuffle_array.rb)
* [Single Number](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/single_number.rb)
* [Sort Squares Of An Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/sort_squares_of_an_array.rb)
* [Two Sum](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/two_sum.rb)
* [Two Sum Ii](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/two_sum_ii.rb)

View file

@ -0,0 +1,61 @@
# 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}
#
# 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
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(n^2)
#
def single_number(nums)
nums.find do |num|
nums.count(num) == 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