LeetCode 1. Two Sum Python Solution

本文解析了LeetCode上的经典问题“两数之和”,提供了两种解决方案:一种是时间复杂度为O(n^2)的暴力解法;另一种是利用dict数据结构实现的时间复杂度为O(n)的高效解法。

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

此题目对应于 LeetCode 1

此题目对应于1. 两数之和

题目要求:

 

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.

给一个数组和一个数值,数组中有两个元素的和等于给定数值,求该两个元素在原数组中对应下标

这里我提供2个解法

解法1:粗暴解法,时间O(n^2),LeetCode运行时间 4945 ms

 

class Solution(object):
    def twoSum(self, nums, target):
        if len(nums)<2:
            return None
        if len(nums)==2:
            return [0,1]
        for i in range(len(nums)):
            left = nums[i]
            for j in range(i+1,len(nums)):
                right = nums[j]
                if left+right == target:
                    return [i,j]

 

解法2:采取辅助的dict数据结构,只需进行一次遍历,时间O(n),LeetCode运行时间 35ms

值得注意的是判断某个key是否存在于dict中的时间复杂度是O(1)的,dict采用了hash的算法。

class Solution(object):
    def twoSum(self, nums, target):
        if len(nums)<2:
            return None
        if len(nums)==2:
            return [0,1]
        dic = {}#key:target-num,补数,value:补数所在的位置
        for i in range(len(nums)):
            if nums[i] in dic:
                return [dic[nums[i]],i]
            else:
                dic[target-nums[i]] = i

 

 

 

 

 

参考文章

 

https://discuss.leetcode.com/topic/23004/here-is-a-python-solution-in-o-n-time

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值