python为什么用两个等于号_刷Leetcode学python(一)两数之和

本代码来自好友詹神公众号《小詹学python》

原题:

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.

题目大意:

给出一个数字列表和一个目标值(target),假设列表中有且仅有两个数相加等于目标值,我们要做的就是找到这两个数,并返回他们的索引值。

例如:

方法一:两层循环

def twoSum(nums, target):

""":type nums: List[int]:type target: int:rtype: List[int]"""

result = []

for i in range(len(nums)):

for j in range(i+1, len(nums)):

if nums[i] + nums[j] == target:

result.append(i)

result.append(j)

return result

我们接着来调用twoSum函数

twoSum([2, 7, 11, 15],9)

可以看到结果是列表的第一个索引和第二个索引的值相加等于9

这个题目,是非常有意义的,我们可以学习到python中如何定义函数、如何传递实参、for循环和if语句的结合用法,以及python当中操作列表的方法。

方法二:一层循环

因为我们知道有且仅有一个解;我们可以通过判断target与某一个元素的差值是否也在列表之中即可,

def secondtwoSum(nums, target):

"""

:type nums: List[int]

:type target: int

:rtype: List[int]

"""

result = []

for i in range(len(nums)):

oneNum = nums[i]

twoNum = target - oneNum

if twoNum in nums:

j = nums.index(twoNum)

if i != j:

result.append(i)

result.append(j)

return result

同样,我们传入实参来调用secondtwoSum函数

同样可看到结果是列表的第一个索引和第二个索引的值

其相加会等于target的值9

往期精彩回顾

图片摄于2017年12月24日于江西明月山

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值