Welcome to the Monastery | |
PerlMonks |
Re: LeetCode Problem #1 - Two Sum - Improve and/or discuss.by syphilis (Archbishop) |
on Jan 24, 2022 at 06:02 UTC ( [id://11140777]=note: print w/replies, xml ) | Need Help?? |
Cheers, Rob Update: When I first looked at this challenge, I noticed that the values in the first example were ordered from lowest to highest - which enables the opportunity to halve the maximum number of trial additions that will be needed. (This could be quite a saving on lengthy arrays of values.) So I went ahead and coded up a procedure that worked quite nicely on sorted arrays. Then I noticed that there was no guarantee that the input arrays would be pre-sorted. Ok ... I'll just have to sort the input array first. (And don't worry that the cost of doing that probably outweighs the advantage of reduced additions.) And then I woke up to the fact that I had to return the indices of the 2 values, not the 2 actual values. Ok ... I can pre-process the original input array so that I keep track of the indices of the values, and then return the appropriate index values. While doing this, I can remove duplicates from the input array - so it's not all additional cost. By the time I finished, I felt like the only man to not Escape from Stalag Luft 112B. But I posted anyway - as testament to the dangers of obstinacy and determination ;-)
In Section
Seekers of Perl Wisdom
|
|