两数之和 python_LeetCode两数之和-Python<一>

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

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

示例:

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

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

所以返回 [0, 1]

解法一

求差值,判断差值是否在nums数组里

classSolution:deftwoSum(self, nums, target):""":type nums: List[int]

:type target: int

:rtype: List[int]"""n=len(nums)for x inrange(n):

b= target-nums[x]if b innums:

y=nums.index(b)if y!=x:returnx,y

时间复杂度:O(n2),空间复杂度:O(1) (补充:python中list对象的存储结构采用的是线性表,因此其查询复杂度为O(n) 也就是 if b in nums 时间复杂度是O(n))

994461-20180703183209761-1512538758.png

解法二

求差值、把差值存进字典里作为键、索引作为值,第一次循环理解:d[7]=0 即字典d={7:0},表示为索引0需要数组里值为7的元素配对。 if 判断是否为前面元素所需要配对的值 , 是则返回两个索引值。(补充:nums[x] in d 是判断值是否在字典某个key里面)

classSolution:deftwoSum(self, nums, target):""":type nums: List[int]

:type target: int

:rtype: List[int]"""n=len(nums)#创建一个空字典

d ={}for x inrange(n):

a= target -nums[x]#字典d中存在nums[x]时

if nums[x] ind:returnd[nums[x]],x#否则往字典增加键/值对

else:

d[a]=x#边往字典增加键/值对,边与nums[x]进行对比

时间复杂度:O(1) 、空间复杂度O(n) (补充:dict对象的存储结构采用的是散列表(hash表),其在最优情况下查询复杂度为O(1))

994461-20180703184735893-1183255893.png

解法三

暴力循环、不多说

classSolution:deftwoSum(self, nums, target):""":type nums: List[int]

:type target: int

:rtype: List[int]"""

#用len()方法取得nums列表的长度

n =len(nums)#x取值从0一直到n(不包括n)

for x inrange(n):#y取值从x+1一直到n(不包括n)

#用x+1是减少不必要的循环,y的取值肯定是比x大

for y in range(x+1,n):#假如 target-nums[x]的某个值存在于nums中

if nums[y] == target -nums[x]:#返回x和y

returnx,y

时间复杂度:O(n2)、空间复杂度:O(1)

994461-20180703184947082-1395404662.png

执行时间明显多于一和二。

性能:解法二>解法一>解法三 。(补充:不能根据这个图片的执行用时比较,应该从时间复杂度比较)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值