LeetCode/study-plan/data-structure/day-02/two-sum.rb
Matej Focko 5d622d4583
data-structure(i): add day 2 and rename day 1
Signed-off-by: Matej Focko <mfocko@redhat.com>
2022-01-20 15:42:43 +01: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