Skip to content

Commit

Permalink
twosum problem with elixir
Browse files Browse the repository at this point in the history
  • Loading branch information
xsami committed Dec 29, 2023
1 parent 6f379ea commit d52d9af
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions TwoSum/twoSum.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Two sum problem by leetcode: https://leetcode.com/problems/two-sum/description/
defmodule Solution do
@spec two_sum(nums :: [integer], target :: integer) :: [integer]
def two_sum(nums, target) do
map = nums |>
Enum.with_index |>
Enum.reduce(%{}, fn({n, i}, prev) -> Map.put(prev, n, i) end)
nums |>
Enum.with_index |>
Enum.reduce([], fn({cur_value, i}, prev) ->
if prev === [] do
sub = target - cur_value
if map[sub] != nil && map[sub] != i do
[i, map[sub]]
else
prev
end
else
prev
end
end)
end
end

0 comments on commit d52d9af

Please sign in to comment.