Two Sum
Description:
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.
Example
numbers=[2, 7, 11, 15], target=9
return [0, 1]
Challenge
Either of the following solutions are acceptable:
O(n) Space, O(nlogn) Time
O(n) Space, O(n) Time
Code:
1.暴力解法
class Solution:
"""
@param: numbers: An array of Integer
@param: target: target = numbers[index1] + numbers[index2]
@return: [index1 + 1, index2 + 1] (index1 < index2)
"""
def twoSum(self, numbers, target):
# write your code here
# O(n^2)
for i in range(len(numbers)) :
for j in range(i+1, len(numbers)) :
if numbers[i] + numbers[j] == target :
return [i]+[j]
2.使用hash map
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):
# write your code here
hashMap = {}
for i in range(len(numbers)):
hashMap[numbers[i]] = hashMap[numbers[i]] + 1 if numbers[i] in hashMap else 1
res = []
for i in range(len(numbers)):
if hashMap[numbers[i]]<=0:
continue
else:
hashMap[numbers[i]] -= 1
secondPara = target-numbers[i]
if secondPara in hashMap and hashMap[secondPara] > 0:
hashMap[secondPara] -= 1
if secondPara == numbers[i]:
return [i,numbers.index(secondPara,numbers.index(secondPara)+1)]
break
res = [i, numbers.index(secondPara)]
return res