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 not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
https://leetcode.com/problems/two-sum/
#!/usr/bin/env python
# coding=utf-8
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self,num,target):
map = {}
j = 1
for i in num:
if (not map.has_key(i)):
map[i]=[];
map[i].append(j);
j = j + 1
for i in num:
ta = target - i
j = map[i][0]
if map.has_key(ta):
if i == ta:
if len(map[ta])> 1:
return j, map[i][1]
else:
if j > map[ta][0]:
j, map[ta][0] = map[ta][0], j
return j,map[ta][0]
if __name__ == '__main__':
s = Solution()
num = [0, 3 , 4, 0]
target = 0
reults = s.twoSum(num, target)
print reults
本文介绍了一种解决两数之和问题的算法实现。给定一个整数数组及目标值,找出数组中两个数相加等于目标值的下标。文章通过Python代码详细展示了如何寻找这两个数并返回其下标。
8414

被折叠的 条评论
为什么被折叠?



