LeetCodeOJ Two Sum (python)

来源:互联网 发布:2017学生空间七天网络 编辑:程序博客网 时间:2024/05/17 09:01


题目:

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



测试时给定给定输入为一个列表,求列表中两元素的和为目标的两值所在索引位置。

思路:先将列表中元素按值和索引位置存入字典中,在字典中索引目标,并返回所在位置。具体见代码:

class Solution:    # @return a tuple, (index1, index2)    def twoSum(self, num, target):        l=len(num)        result=[0,0]        dict1={}        if l<2:            return tuple(result)        else:            for i,val in enumerate(num):                dict1[val]=i                        for j in range(0,l):                if (target-num[j]) in dict1 and j!=dict1[target-num[j]]:                    result[0]=min(j+1,dict1[target-num[j]]+1)                    result[1]=max(j+1,dict1[target-num[j]]+1)        return tuple(result)  


0 0
原创粉丝点击