leetcode01 Two Sum 寻找列表中和为定值的元素位置

本文介绍LeetCode经典题目“两数之和”的两种解法:一种是双层循环遍历,另一种是利用哈希表实现的高效解法。通过这两种方法对比,展示如何优化算法提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刷刷leetcode。

problem description:

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.

给定一个列表,找出和为给定值的两个元素的位置,我们假设只有一个结果,并且一个值只能使用一次,下面是例子:

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
我的解法(很蠢):

# my solution
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                while nums[i] + nums[j] == target:
                    return i,j

sol = Solution()
sol.twoSum([3,2,4],6)
别人的优质解法,复杂度为O(n)

class Solution(object):
    def twoSum(self, nums, target):
        if len(nums) <= 1:
            return False
        buff_dict = {}
        for i in range(len(nums)):
            if nums[i] in buff_dict:
                return [buff_dict[nums[i]], i]
            else:
                buff_dict[target - nums[i]] = i
                print buff_dict

sol = Solution()
sol.twoSum([3,2,6,5],7)

解读一下别人的优质解法:

新建空字典buff_dict,将前面出现过的目标值-数字作为key,数字的位置作为value存入buff_dict,打个比方列表是[2,4,5,3],定值是7。我们从位置0开始,先存入{7-2:0},再存入{7-4:1},所以buff_dict现在是{5:0,3:1},只要后面出现5或者3,就说明我们找到了元素和为8的两个元素。

总结:生成一个以目标值减去前面出现的元素为key,出现的元素位置为value的字典。这样我们就知道,前面的元素需要这些值就可以满足和为定值的条件了,后面只要出现一个,就直接把value和当前值的位置作为结果返回。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值