1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/problems/rb/two-sum.rb
Matej Focko 333866d1bc
chore: split solutions by language
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-06-02 17:19:02 +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