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

leetcode-Two sum(最佳思路以及python代码实现)

2018-03-22 10:17 579 查看
1、Two sum
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].答案:使用hashtable,建立数组值和下标的键值对,在python中相当于使用dict来存储,dict的key是数组的值,数组的下标是dict的value。
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int 
        :rtype: List[int]
        """
        dict = {} # 定义一个字典
        for i in xrange(len(nums)): # 遍历数组
            x = nums[i]  # 取当前数组的值
            if target-x in dict:  # 如果target减去当前值的差在字典的key中可以找到,直接可以返回dtarget-x对应的值,也即下标
                return (dict[target-x], i)  # 返回当前下标和找到的下标
            dict[x] = i   # 将数组值和下标数存入dict
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python  two sum