leecode001——两数之和

 1.循环遍历求解

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        leng = len(nums)
        for i in range(leng):
            nums2 = target - nums[i]
            if nums2 in nums[i+1:]:
                return [i,nums[i+1:].index(nums2)+i+1]

从第一个元素开始遍历,然后查看target-nums元素是否在剩下的元素里,如果有返回索引值。

len():返回对象长度或个数。

list.index(obj):用于返回列表中某个obj第一个匹配项的索引值。该方法返回查找对象的索引位置,如果没有找到对象则抛出异常。

range(start, stop[, step]):创建一个整数列表,一般用于for循环中。可以用于重复打印。

for i in range(3):
	print('加油,你可以的!!!')
 
>>>加油,你可以的!!!
>>>加油,你可以的!!!
>>>加油,你可以的!!!

 2.哈希表

建立一个哈希表,对于每一个 x,我们首先查询哈希表中是否存在 target - x,存在返回索引值,不存在将 x 插入到哈希表中,即可保证不会让 x 和自己匹配。

不需要遍历两遍,一边查询一边建表。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashtable = dict()
        for i, num in enumerate(nums):
            if target - num in hashtable:
                return [i, hashtable[target-num]]
            hashtable[nums[i]] = i
enumerate(sequence, [start=0]):将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

 哈希表用时仅32ms, 循环遍历勇士316ms,将近10倍,但是哈希表占内存大,用空间换时间

https://blog.csdn.net/qq_41800366/article/details/86495166

https://blog.csdn.net/ISPEAKER/article/details/100126565

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值