0001 Two Sum
Solved at: 220710
Question
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Solution
So the first obvious answer is to iterate twice. This finishes calculations in time.
However, this gives a timeout.
Improved
I used Python Dictionary to store complementing values. Python Dictionary will have access time for most cases. This solution will run in time.
- One caveat: depending on the hash function, it can go as bad as .
Results
Runtime
- 60 ms, faster than 97.16% of Python3 online submissions for Two Sum.
Memory Usage
- 15.4 MB, less than 14.24% of Python3 online submissions for Two Sum.
Other Answers Online
- Sort first,
- For all elements,
- Perform binary search
- In total:
Backlinks (2)