两数之和 python_[LEEDCode][001][简单] – 两数之和(Two Sum)

啦啦啦,欢迎开启LeetCode刷题的旅程。

这将是一段漫长而又艰辛的旅程,这是一条攀登珠穆朗玛的皑皑雪山路,这是通向One Piece宝藏的伟大航路,这是无比残酷的修罗场。

但请不要害怕,我们一起努力,必将一路披荆斩棘,将各位带到成功的彼岸,不过一定要牢记的是,不要下船,不要中途放弃,要坚持,要自我修炼,不断成长!那么,起航吧~

这道Two Sum的题目作为LeetCode的开篇之题,乃是经典中的经典,正所谓‘平生不识TwoSum,刷尽LeetCode也枉然’。

就像英语单词书的第一个单词总是Abandon一样,很多没有毅力坚持的人就只能记住这一个单词,所以通常情况下单词书就前几页有翻动的痕迹,后面都是崭新如初,道理不需多讲,鸡汤不必多灌,明白的人自然明白。

废话不多说,开始进入答题模式——

两数之和 Two Sum

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.

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

1

2

3

4

给定nums=[2,7,11,15],target=9

因为nums[0]+nums[1]=2+7=9

所以返回[0,1]

解答

class Solution:

def twoSum(self, nums, target):

"""

:type nums: List[int]

:type target: int

:rtype: List[int]

"""

for i in range(len(nums)):

if target - nums[i] in nums:

for j in range(len(nums)):

if i != j and target - nums[i] == nums[j]:

return [i, j]

1

2

3

4

5

6

7

8

9

10

11

12

classSolution:

deftwoSum(self,nums,target):

"""

:type nums: List[int]

:type target: int

:rtype: List[int]

"""

foriinrange(len(nums)):

iftarget-nums[i]innums:

forjinrange(len(nums)):

ifi!=jandtarget-nums[i]==nums[j]:

return[i,j]

输出结果

我的输入

[2,7,11,15]

9

1

2

[2,7,11,15]

9

我的答案

[0,1]

1

[0,1]

喜欢 (0)赏分享 (0)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值