Python_百题大冲关_7.查找两个总和为特定值的索引

7.查找两个总和为特定值的索引

题目描述

给定一个数组,找到两个总和为特定值的索引。
例如给定数组 [1, 2, 3, -2, 5, 7],给定总和 7,则返回索引 [1, 4]。

思路一

O(n²)暴力

代码

class Solution(object):

    def two_sum(self, nums, val):
        if nums is None or val is None:
            raise TypeError('nums or target cannot be None')
        if not nums:
            raise ValueError('nums cannot be empty')
        lenth = len(nums)
        res = []
        for i in range(lenth):
            temp = val - nums[i]
            for j in range(lenth):
                if nums[j] == temp:
                    res.append(i)
                    res.append(j)
                    return res
        return None

思路二

使用list内置函数 O(n²)

代码

class Solution(object):

    def two_sum(self, nums, val):
        if nums is None or val is None:
            raise TypeError('nums or target cannot be None')
        if not nums:
            raise ValueError('nums cannot be empty')
        lenth = len(nums)
        res = []
        for i in range(lenth):
            temp = val - nums[i]
            if temp in nums:
                res.append(i)
                res.append(nums.index(temp))
                return res
        return None

思路三

哈希表

代码

class Solution(object):

    def two_sum(self, nums, val):
        if nums is None or val is None:
            raise TypeError('nums or target cannot be None')
        if not nums:
            raise ValueError('nums cannot be empty')
        cache = {}
        for index, num in enumerate(nums):
            cache_val = val - num
            if num in cache:
                return [cache[num], index]
            else:
                cache[cache_val] = index
        return None
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值