您的位置:首页 > 编程语言 > Python开发

[leetcode]-[Two Sum]-python实现

2015-04-07 21:35 423 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: