每天一更 Leecode每日一题--TwoSum

题目 Twosum

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


解题

第一次:
根据题目的提示写了一段代码

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        lst = []
        for i in range(0,len(nums)-1):
            if nums[i] + nums[i+1] == target:
                lst.append(i)
                lst.append(i+1)
        return lst

提交代码显示 解 读 错 误 \color{red}{解读错误}
第一次提交
发现问题是一层for循环不够,改写代码
第二次:
for循环再套一次循环

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        lst = []
        l = len(nums)
        for i in range(0,l):
            for j in range(i+1,l):
                if nums[i] + nums[j] == target:
                    lst.append(i)
                    lst.append(j)
        return lst

这次显示 超 出 时 间 限 制 \color{red}{超出时间限制}
超出时间限制
这就是没有考虑算法,而且显然两层for循环太浪费时间,这时候就考虑怎样能减少代码运行时间。
第三次:
对上面程序进行再次改写,运用python特有的 字 典 \color{red}{字典}

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = dict()
        l = len(nums)
        for i in range(0, l):
            temp = target - nums[i]
            if temp in dic:
                return [dic[temp], i]
            dic[nums[i]] = i

这次再运行代码,运行成功。
第三次运行第四次:
python中还有个函数是enumerate
套for循环使用enumerate函数

>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     print i, element
... 
0 one
1 two
2 three

这题解法还可以是:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
            dic = dict()
            for i, ele in enumerate(nums):
                if target - ele in dic:
                    return [dic[target - ele], i]
                dic[ele] = i

提交代码
enumerate函数
不过没想到enumerate()函数运行速度居然没提升…


总结

这题运用的是 哈 希 表 \color{blue}{哈希表}
哈希表简单来说就是能把值和地址对应起来,就像python里的字典有value和key,一个value对应一个key值,或者是像上面enumerate()函数用for循环时i和ele。

提醒一下
上面代码都是可以直接在Leecode里实现
如果是pycharm或其他软件实现需要改代码,给个例子:

def twoSum(nums, target):
    dic = dict()
    for i, ele in enumerate(nums):
        if target - ele in dic:
            return [dic[target - ele], i]
        dic[ele] = i

nums = [3, 2, 4]
target = 6
out = twoSum(nums, target)
print(out)

第一天结束
over

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值