mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 09:59:41 +01:00
30 lines
694 B
Ruby
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
|