欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

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

发布时间:2024/10/8 python 37 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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日于江西明月山

总结

以上是生活随笔为你收集整理的python为什么用两个等于号_刷Leetcode学python(一)两数之和的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。