Leetcode【1】:Two Sum

本文详细介绍了解决LeetCode两数之和问题的三种方法:暴力法、夹逼法和字典查找法。每种方法都包括时间复杂度、空间复杂度分析,并提供了代码实现。通过对比不同方法的性能,帮助读者理解如何在实际编程中选择最适合的解决方案。

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

问题

https://leetcode.com/problems/two-sum/

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 sameelement twice.

Example:

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解析

题目给定一个int数组和target,找到两数之和=target,返回其下标(从0开始,且index1<index2)

一:暴力法

两层循环暴力求解,能AC,时间性能5%

时间O(n^{2}),空间O(1)

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

二:夹逼法

考虑到排序有可能降低时间开销,然后前后夹逼,使用贪心的思路去搜索:首尾之和>target,则尾部左移;首尾之和<target,则头部右移。

排序会丢失原始下标,必须存储。

时间O(n*log{n}),空间O(n)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        //构造带原始index的元组,排序
        numPairs = []
        for i in range(len(nums)):
            numPairs.append((nums[i], i))
        numPairs = sorted(numPairs, key = lambda x:x[0], reverse=False)
        
        //前后夹逼搜索
        start, end = 0, len(numPairs) - 1
        while start < end:
            if numPairs[start][0] + numPairs[end][0] > target:
                end -= 1
            elif numPairs[start][0] + numPairs[end][0] < target:
                start += 1
            else:
                ret = [numPairs[start][1], numPairs[end][1]]
                ret.sort()
                return ret
        return []

 

三:字典查找

求两数之和=target,即遍历数组元素n时,在剩余元素中查找target-n的存在性,字典可破:一边插入字典,一边查找数差

时间O(n),空间O(n)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        numDict = {}
        for index in range(0, len(nums)):
            if target - nums[index] in numDict:
                return [numDict[target - nums[index]], index]
            else:
                numDict[nums[index]] = index
        return []

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值