Leetcode-2sum-python

本文介绍了一种解决LeetCode经典题目“两数之和”的高效算法。通过使用Python字典,实现O(n)的时间复杂度,快速找到目标值对应的两个数的下标。

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

Leetcode 2sum python

Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Description

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

初始版本的思路
依次将两个数相加,由于题目中说明只存在一对答案,因此如果存在符合条件的两个下标,就是需要的答案。
测试未通过
leetcode要求需要满足时间复杂度。

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

leetcode上提供的一种O(n)的python解法,使用字典, python字典采用hash方式。
解题思路
建立一个字典,依次比较列表中的元素。如果字典的键中不存在该元素,就将target - nums[i]作为字典的键,并将对应的下标作为值;如果字典键中存在该元素,则说明字典中存在符合要求的对应元素,通过buff_dict[nums[i]]提取出另一个元素的下标。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值