python 两数之和

两数之和 python实现

解法1

不用说耗时长,复杂度 O ( n 2 ) O(n^2) O(n2)

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

解法2

由于数组.index函数复杂度为O(1),整体复杂度降为O(n)看起来而已,其中target - nums[i] in nums 操作复杂度为O(n)

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n  = len(nums)
        for i in range(n):
            if target - nums[i] in nums:
                y = nums.index(target - nums[i])
                if  i != y:
                    return [i,y]

解法3

通过空间换时间的思想,建立字典(内部实现为hash map)查找速度O(1)。
空间复杂度为O(n)
#TODO 不是那么清楚为什么解法3比解法2快那么多,个人认为:
python中list对象的存储结构采用的是线性表,因此其查询复杂度为O(n),而dict对象的存储结构采用的是散列表(hash表),其在最优情况下查询复杂度为O(1)。

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for x in range(len(nums)):
            rest = target - nums[x]
            #字典d中存在nums[x]时,就代表rest找到了,返回rest的下标,再根据字典找到rest的另一半的下标
            if nums[x] in d:
                return d[nums[x]],x
            #否则往字典增加键/值对,值是nums[x]的索引,
            else:
                d[rest] = x

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值