leetcode python3 简单题1.Two Sum

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第一题

(1)题目
英文:
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 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
(2)解法
① 使用enumerate(单循环)(耗时:1636ms,内存:14.5M)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for indx, num in enumerate(nums):
            if target - num in nums:
                if indx == nums.index(target - num):
                    continue
                return [indx, nums.index(target - num)]

注意:
1.如果nums=[3,4,5],target=6,那么第一个6-3=3是它本身,而不是两个不同数,所以要排除掉这种情况,否则无法AC,当然这个还有个大前提是,nums没有重复的元素哦。
2.list类型的.index只会返回第一个index,要想返回所有的index,使用:

[i for i in range(len(list)) if list[i] == 某个数]

3.twoSum(self, nums: List[int], target: int) -> List[int]:
这里只是对输入变量和函数输出值类型的说明,并不会提示报错。

② 使用enumerate(双循环)(耗时:5384ms,内存:14.6M)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for indx1, num1 in enumerate(nums):
            for indx2 in range(indx1+1, len(nums)):
                if num1 + nums[indx2] == target:
                    return [indx1, indx2]

注意:
1.这种结构就显然过滤掉了①中注意1.中的情况了,相当于排列组合

③ 使用hash map(字典dict)(耗时: 64ms,内存:15M)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}
        for indx, num in enumerate(nums):
            if target - num in hashmap:
                return [indx, hashmap[target - num]]
            hashmap[num] = indx

注意:
1.这种结构就显然也能过滤掉①中注意1.中的情况

本人现在的研究方向是:
图像的语义分割,如果有志同道合的朋友,可以组队学习
haiyangpengai@gmail.com qq:1355365561

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值