题解 | #两数之和# Erlang用map强匹配用时快 内存消耗少

两数之和

http://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f

解题思路

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

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

代码

-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.
全部评论

相关推荐

评论
3
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务