1.LeetCode1 TwoSum 随笔

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以及下标

原文地址:https://www.cnblogs.com/19991201xiao/p/8395319.html