leetcode两数之和python

在编写leecode上的算法第一题“两数之和”时,遇到了一些问题,如下:

1.参数丢失

>>>Solution.twosum([2,3,4,5],8)

TypeError: twosum() missing 1 required positional argument: 'target'

原因:没有创建对象

解决:

>>>a = Solution()      #括号很重要

>>>a.twosum([2,3,4,5],8)

 

2.超出时间显示

原因:时间复杂度高 O(n2)

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

解决: 降低时间复杂度,O(n) 

class Solution:  
    def twoSum(self,nums, target):  
        """ 
        :type nums: List[int] 
        :type target: int 
        :rtype: List[int] 
        """  
        #用len()方法取得nums列表长度  
        n = len(nums)  
        #创建一个空字典  
        d = {}  
        for x in range(n):  
            a = target - nums[x]  
            #字典d中存在nums[x]时  
            if nums[x] in d:  
                return d[nums[x]],x  
            #否则往字典增加键/值对  
            else:  
                d[a] = x  
        #边往字典增加键/值对,边与nums[x]进行对比  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值