【leetcode每日一题】【2019-04-03】1. 两数之和

1. 两数之和

题目地址: https://leetcode-cn.com/problems/two-sum/


给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

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

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

笨办法,从第一个数字开始,用target减去这个数字,如果结果在列表中,则返回这2个数字的位置,如果不在,则继续。

第一版代码如下:


class Solution:

    def twoSum(self, nums: List[int], target: int) -> List[int]:

        for i in nums:

    num=target-i

if num!=i and num in nums:

    print([nums.index(i),nums.index(num)])

结果任务提交失败了,有个Bug, 如果是2个相同的数字,则不会出现结果。我来我的意图是跳过本来的数字,但是我考虑的有点问题。

当提交 nums=[3,3] target=6 的时候没有输出结果。

所以我考虑再复制一个List出来,然后把当前的数据remove之后,再检查相减的数字是否在List中。

第二版代码如下:


def twoSum(self, nums: List[int], target: int):

    for i in nums:

        num = target - i

        new_target = nums.copy()

        new_target.remove(i)

        if num in new_target:

            post1 = nums.index(i)

            post2 = new_target.index(num)

            if post2>=post1:

                post2=post2+1

            return ([post1,post2])

            break

执行用时 : 2740 ms, 在Two Sum的Python3提交中击败了34.79% 的用户

内存消耗 : 13.5 MB, 在Two Sum的Python3提交中击败了0.84% 的用户

看了下解题思路,又改版了下

第三版代码如下:


class Solution:

    def twoSum(self, nums: List[int], target: int):

        tmp_map = {}

        for i in range(0,len(nums)):

            num = target - nums[i]

            if num in tmp_map:

                return ([tmp_map[num], i])

                break

            tmp_map[nums[i]] = i

执行用时 : 84 ms, 在Two Sum的Python3提交中击败了56.62% 的用户

内存消耗 : 14.4 MB, 在Two Sum的Python3提交中击败了0.84% 的用户

遇到的一些问题

  • python2 的 list 对象没有 copy 方法, python3 有

  • list.index 可以通过 object 返回 index

  • range() 产生的数据是 ( ] 的

  • Python的变量是不需要定义类型的,但是如果希望限定类型的话,可以使用 类型注解(type hints) , 引入 import typing

猜你喜欢

转载自blog.csdn.net/action825/article/details/89000352