【LeetCode - Python】 1.两数之和(Easy)

01:两数之和

题目:
在这里插入图片描述
代码:

class Solution:

    # 暴力法,遍历
    def twosum(self,nums,target):
        """
        type nums: list[int]
        type target : int
        rtype : list[int]
        """
        for i in nums:    
            start_index = nums.index(i)     #获得本次循环的初始坐标;
            j = target - i                  #获得初始值与target差距,需要再次比较来看差值是否存在于nums
            next_index = start_index + 1    #下次循环的初始坐标
            temp_nums = nums[next_index: ]  #python专用,创建新arr,在nums基础上,创建next_index 开始,一直到结束;
            if j in temp_nums:              #做判断差距,是否存在于剩下的nums;
                return(nums.index(i),next_index+temp_nums.index(j)) #如果存在,返回:初始坐标,结果坐标
    #哈希表法
    def twoSum(self,nums,target):
        """
        type nums: list[int]
        type target : int
        rtype : list[int]
        """
        dict = {}                               #先创建空表
        for i in range(len(nums)):              #从0开始遍历
            if target - nums[i] not in dict:    #如果target -  此时遍历值 得到的值不在表内
                dict[nums[i]] = i                   #向表内添加:此时的值,对应坐标
            else:                               #如果target -  此时遍历值 得到的值在表内
                return [dict[target-nums[i]],i]     #返回减去的值的坐标(先于当前遍历值被添加,坐标小),当前遍历值的坐标

nums = [2,7,11,15]
target = 9
t = Solution()
rtAns = t.twoSum(nums,target)
print(rtAns)

参考:
[1]: 【LeetCode in Python 1. Two Sum LeetCode - Michelle小梦想家】 B站链接

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值