in reply to LeetCode Problem #1 - Two Sum - Improve and/or discuss.
UPDATE 1: removed buggy " -1" from (0..$#$inp -1); deleted unnecessary variable @solutions.sub twosum_NetWallah{ my ($inp, $target)=@_; my %targ_idx = map { $inp->[$_] => $_ } 0..$#$inp; for (0..$#$inp){ next unless defined ( my $other=$targ_idx{ $target - $inp->[$_] } + ); next if $other == $_; return [ $other > $_ ? ($_, $other) : ($other, $_) ]; } return undef; } # Test NetWallah.. for my $test (@tests) { is_deeply sort_arrayref(twosum_NetWallah ($test->[INPUT], $test->[TARGET +])), sort_arrayref($test->[EXPECTED]); }
UPDATE 2: I did try to benchmark the code - kcott's runs ~ 40% faster, so I was surprised!
However- After adding this test case:
kcott's code fails that test case, but mine passes.[[-5,-3,1,4,7], 1, [1,3]],
BTW - thanks for setting up this challenge!
"If you had better tools, you could more effectively demonstrate your total incompetence."
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: LeetCode Problem #1 - Two Sum - Improve and/or discuss.
by kcott (Archbishop) on Jan 25, 2022 at 20:12 UTC | |
|
Re^2: LeetCode Problem #1 - Two Sum - Improve and/or discuss.
by ikegami (Patriarch) on Jan 25, 2022 at 14:40 UTC |