我试图解决LeetCode中的this小问题:
-module(two_sum).
-export([main/2]).
-spec main(List :: list(), Target :: non_neg_integer()) -> list().
%%%==================================================================
%%% Export
%%%==================================================================
main(List, Target) ->
P = [{string:str(List, [X]), string:str(List, [Y]), X + Y} || X <- List, Y <- List, Y > X andalso X + Y =:= Target],
io:format("Result: ~w~n", [P]).
%%[X + Y || X <- List, Y <- List, Y > X].
%%iterate(List, Target, 0, {}).
%%%==================================================================
%%% Internal
%%%==================================================================
iterate([], _Target, _Sum, _Result) -> {};
iterate([H | T], Target, Sum, Result) ->
%%io:format("H >> ~w; T >> ~w, Target >> ~w~n", [H, T, Target]).
Acc = Sum + H,
case Acc =:= Target of
true -> erlang:append_element(Result, H);
false -> iterate(T, Target, Acc, Result)
end.
我的问题是:
{string:str(List, [X])
,但我不确定这是否正确,尽管它已完成工作。R = [{1,2,9},{1,3,13},{1,4,17},{2,3,18},{2,4,22},{3,4,26}]
,我如何模仿{1,2,9}
的匹配,知道9
是Target
?我试过了[{X1, X2, Target}] = R
......但它并不喜欢它!答案 0 :(得分:1)
这个怎么样?对于每个元素,检查其与列表中每个后续元素的总和,并带有两个索引,用于在找到匹配项时向用户报告。
find_indices(Target, [_H | T] = L) ->
find_indices(Target, L, T, 0, 1).
find_indices(_Target, [_], [], _I, _J) ->
io:format("No match~n");
find_indices(Target, [_Curr | LeftRest], [], I, _J) ->
find_indices(Target, LeftRest, tl(LeftRest), I + 1, I + 2);
find_indices(Target, [Curr | _LeftRest], [Other | _RightRest], I, J)
when Target =:= Curr + Other ->
io:format("Match at indices ~p and ~p: ~p + ~p = ~p~n",
[I, J, Curr, Other, Target]),
ok;
find_indices(Target, L, [_Other | RightRest], I, J) ->
find_indices(Target, L, RightRest, I, J + 1).
示例:
1> index:find_indices(7, [1,2,3,4,5,6]).
Match at indices 2 and 3: 3 + 4 = 7
ok
2> index:find_indices(11, [1,2,3,4,5,6]).
Match at indices 4 and 5: 5 + 6 = 11
ok
3> index:find_indices(12, [1,2,3,4,5,6]).
No match
ok
4> index:find_indices(4, [1,2,3,4,5,6]).
Match at indices 0 and 2: 1 + 3 = 4
ok