Algorithm Practice - Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are zero-based.

http://www.lintcode.com/problem/two-sum/

Solution #1 - Brute Force search. O(n) Space, O(n^2) time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
"""
@param numbers: An array of Integer
@param target: target = numbers[index1] + numbers[index2]
@return: [index1, index2] (index1 < index2)
"""
def twoSum(self, numbers, target):
for i, n in enumerate(numbers):
for j, m in enumerate(numbers[i+1:], i+1):
if n + m == target:
return [i, j]
return [-1, -1]

Solution #2 - Double pointer. O(n) Space, O(nlogn)time

Solution #3 - Hash. O(n) Space, O(n)time

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
"""
@param numbers: An array of Integer
@param target: target = numbers[index1] + numbers[index2]
@return: [index1, index2] (index1 < index2)
"""
def twoSum(self, numbers, target):
d = {}
for i in range(len(numbers)):
if target - numbers[i] in d:
return [d[target - numbers[i]], i]
d[numbers[i]] = i
return [-1, -1]