my-solutions/leetcode/0001-two-sum/elixir/lib/two_sum.ex

23 lines
635 B
Elixir

defmodule Solution do
@spec two_sum(nums :: [integer], target :: integer) :: [integer]
def two_sum(nums, target) do
process_num(nums, target)
end
@spec process_num(
nums :: [integer],
target :: integer,
head_idx :: integer,
indexes :: %{integer => integer}
) :: [integer]
defp process_num([head | tail], target, head_idx \\ 0, indexes \\ %{}) do
first_idx = indexes[target - head]
if first_idx != nil do
[first_idx, head_idx]
else
indexes = Map.put(indexes, head, head_idx)
process_num(tail, target, head_idx + 1, indexes)
end
end
end