Leetcode001 两数之和

今天开始刷LeetCode上边的题。英文不差但是中文网站的毕竟读着效率高一点。python小白,就开始边问度娘边在PyCharm上做题了。人家说用IDE不好,但是为了先熟练基础知识,就用了IDE。

001 两数之和

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]


想不到什么好办法,就双重for循环吧。在一开始检查一下数是不是大于了target,大于就不用算了。于是提交第一次代码:

class solution:
    def twoSum(self, nums, target):
        dic = []
        for indexi, i in enumerate(nums):
            if i >= target:
                continue

            for indexj, j in enumerate(nums):
                if (j != i) and (i + j == target):
                    dic.append(indexi)
                    dic.append(indexj)
                    return dic

第一次提交,折在了【3,3】 6上。发现是判断条件不合适,应判断nums下标是否相同。

if (j != i) and (i + j == target):

为:

if (indexj != indexi) and (i + j == target):

第二次提交,折在了【0,3,4,0】0上。发现i >=target的判断不合适。删掉了=号。

第三次提交,折在了【-1,-2,-3,-4,-5】 -8上。因为i>target在这里不适用了。索性删掉了这部分判断。

第四次提交,一个超长输入,超时……

于是上网找时间复杂度低的办法。基本思想是只用一个循环遍历nums,剩下的一次“遍历”交给字典来查找。看当前num[x]值距离target差多少,就以它为key,原本的x为value。再检查下一个num[x+1]时,去字典里找key有没有正好差那么多的差。找到就返回坐标。代码:

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]进行对比  
也是学习到了。记录一下备忘!


猜你喜欢

转载自blog.csdn.net/u014292401/article/details/80903765