Two sum problem
Problem
Given N digits, find two numbers whose sum is equal to the given number T.Answer
Using the hashtable, we can easily check if any two numbers are equal to T.
Here is algorithm.
1. Put all numbers into a hashtable, $O(N)$
2. Iterate over the N digits assuming there are in a list.
3. For each number, n, check if T-n exists in the hashtable.
Running time $O(N)$ for hashtable, $O(N log N)$ for map.
The following is the code.
I will post another code implementation if I find better implementation.
1. Put all numbers into a hashtable, $O(N)$
2. Iterate over the N digits assuming there are in a list.
3. For each number, n, check if T-n exists in the hashtable.
Running time $O(N)$ for hashtable, $O(N log N)$ for map.
The following is the code.
Comments
Post a Comment