leetcode python 1复习

leetcode1 

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

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

示例:

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

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

这道题目 一开始的想法是设置两个不重复的指针,当两个数字的和为目标值时,返回这两个指针。
如下:
class Solution(object):
    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[i]+nums[j]==target:
                    return i,j
但是这种明显的可读性很高,容易懂,缺点就是时间代价太多了(n2)
同样的想要时间代价越小,花费的空间代价就更大。
在观看其他人的代码后获得以下思路:
用target-nums 里面的每个值,保存,O(n)空间代价,看得到的值是否存在于原来的nuns里,如果存在,那么输出这两个值的index
代码如下:
class Solution(object):

    def twoSum(self, nums, target):

        """

        :type nums: List[int]

        :type target: int

        :rtype: List[int]

        """

        d = {}

        for i, num in enumerate(nums):

            if target - num in d:

                return [d[target - num], i]

            d[num] = i
# for i ,num in enumerate(nums),调用了enumerate方法,获得一个enumerate对象,可以用两个参数获取其中的index 和里面的对象。


猜你喜欢

转载自www.cnblogs.com/ccgcy/p/9123356.html