当前位置: 移动技术网 > IT编程>脚本编程>Python > 1.LeetCode1 TwoSum 随笔

1.LeetCode1 TwoSum 随笔

2018年02月01日  | 移动技术网IT编程  | 我要评论

178网赚之家,ca4416,西条琉璃40部全集

1:题目描述

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

给出一组数据及一个目标数字,找出这组数据中数字之和为目标数字的两个数字,返回他们的索引位置

2:解题困惑

初次使用python完成题目,对于面向对象还不能充分理解,所以借鉴了网上的例子

3:解题思路

    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        NUM={} #设置一个字典,将输入的数字及对应下标存储到里面
        for index,num in enumerate(nums):  #使用for以及enumerate()函数遍历nums数组
            if target-num in NUM:                    #如果target-num 在NUM字典中
                return (NUM[target-num],index) #返回target-num,以及num的索引位置
            NUM[num]=index                           #向字典中存储num以及下标

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网