in reply to LeetCode Problem #1 - Two Sum - Improve and/or discuss.
I believe this runs in O(n) time. But that's on the presumption that the input list of numbers is already sorted. If it's not, then this solution would have to add a sorting step, which will make it O(n log n).
sub TwoSum { my( $target, @nums ) = @_; # assumption: @nums are already sorted. # caveat: the nums in the list might not be uniq!!! my %num; @num{@nums} = (); # for existence tests. for my $i2 ( reverse( 1 .. $#nums ) ) { my $d = $target - $nums[$i2]; if ( exists $num{$d} ) { # gotta find the _first_ occurrence of this number in the li +st: my($i1) = grep { $nums[$_] == $d } 0 .. $i2-1; return( $i1, $i2 ); } } die }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: LeetCode Problem #1 - Two Sum - Improve and/or discuss.
by kcott (Archbishop) on Jan 25, 2022 at 18:45 UTC | |
|
Re^2: LeetCode Problem #1 - Two Sum - Improve and/or discuss.
by LanX (Saint) on Jan 25, 2022 at 13:44 UTC |