解题思路

记录已遍历元素,用强匹配快速匹配差值的元素索引

哈希表以元素为主键,减少内存消耗

代码

-spec two_sum(Nums :: [integer()], Target :: integer()) -> [integer()].
two_sum(Nums, Target) ->
    Args = catch lists:foldl(fun do_two_sum/2, #{index => 0, target_map => #{}, target => Target, result_list => []}, Nums),
    maps:get(result_list, Args).

do_two_sum(N, Args = #{index := Index, target := Target, target_map := TargetMap}) ->
    case TargetMap of
        #{Target - N := PreIndex} ->
           throw(#{result_list => [PreIndex, Index]});
        _ ->
            Args#{index := Index + 1, target_map := TargetMap#{N => Index}}
    end.