1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00
LeetCode/problems/two-sum.rb
Matej Focko 6c3cfcd876
chore: reorganize files
Signed-off-by: Matej Focko <mfocko@redhat.com>
2022-07-23 12:53:31 +02:00

30 lines
694 B
Ruby

# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
encountered = Hash.new
nums.each_index { |i|
complement = encountered.assoc(target - nums[i])
if complement != nil then
return [complement[1], i]
else
encountered[nums[i]] = i
end
}
end
RSpec.describe "two_sum from" do
it "[2, 7, 11, 15] for 9 is [0, 1]" do
expect(two_sum([2, 7, 11, 15], 9)).to eq([0, 1])
end
it "[3, 2, 4] for 6 is [1, 2]" do
expect(two_sum([3, 2, 4], 6)).to eq([1, 2])
end
it "[3, 3] for 6 is [0, 1]" do
expect(two_sum([3, 3], 6)).to eq([0, 1])
end
end