LeetCode: Find All Duplicates in an Array

Question

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [2,3]

Solution#1

def find_duplicates(nums)
  result = Hash.new(0)
  nums.each do |num|
    result[num] += 1
  end
  result.select{|key, value| value >= 2}.keys
end

Solution#2

def find_duplicates(nums)
  dict = Hash.new(0)
  result = []

  nums.each do |num|
    # every time encounter the same number will increase by one
    dict[num] = dict[num] + 1
    if dict[num] > 1
      result << num
    end
  end
  result
end