leetcode代码对两个数字求和

小白第一天写博客,希望坚持下来,进步吧。
@twoSum
给定一个整型数组和一个目标数字,计算整型数组中两个数字的和,当两个数字的和等于目标数字时,返回这两个数字的索引。
第一种方法:
当然是最笨的方法了,我觉得一般人都可以想到了,对数组进行遍历,计算数组中两个数字的和,如果和目标数字相等,则返回索引,返回的是一个列表。
代码如下:
class Solution:
def twoSum(self, nums, target):
“”"
:type nums: List[int]
:type target: int
:rtype: List[int]
“”"
//定义返回的列表
final_list = []
//遍历数组
for x in range(len(nums)):
//遍历数组的下一个元素
for y in range(x+1,len(nums)):
//判断两个数之和是否等于目标索引
if nums[x] + nums[y] == target:
final_list = [x,y]
return final_list
这种方法运行最慢了,时间复杂度是O(n^2),遍历了两边数组。
第二种方法
在遍历第一遍时,先计算出和第一个数字相加等于目标数字的那个数字,再遍历数组,判断数组中有没有刚才计算的那个数字,如果相等,则返回索引。
和上一种方法比较,这种方法时间复杂度也是O(n^2),其实都差不多。
代码如下:
class Solution:
def twoSum(self, nums, target):
“”"
:type nums: List[int]
:type target: int
:rtype: List[int]
“”"
for i in range(len(nums)):
mid = target - nums[i]
for j in range(i+1,len(nums)):
if nums[j] == mid:
return [i,j]
第三种方法:
用一个字典去保存这个数组,利用enumerate()方法,自动对数组加上索引,将num数组索引值赋值给字典的值,这样就可以根据数组的值很快拿到索引值了。
代码如下:
class Solution:
def twoSum(self, nums, target):
“”"
:type nums: List[int]
:type target: int
:rtype: List[int]
“”"
dictionary = {}
for key, value in enumerate(nums):
complement = target - value
if dictionary.contains(complement):
return [dictionary.get(complement), key]
//num数组的索引值赋值给字典的科研
dictionary[value] = key
例如:输入的数组值为nums = [2,7,11,12],target = 9
第一次循环,key=0,value= 2
Complement=9-2=7
Dictionary[2] = 0 这时字典中会保存{2:0}
第二次循环,key=1,value= 7
Complement=9-7=2
Dictionary[7] = 1 这时字典中会保存{2:0,7:1}相信后边的就能看懂啦
这种的时间复杂度就是O(n),空间复杂度为O(1)。
两个数求和就写到这里了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值