首页 > 编程语言 > 详细

Python版[leetcode]1. 两数之和(难度简单)

时间:2020-02-01 09:53:20      阅读:49      评论:0      收藏:0      [点我收藏+]

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

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

示例:

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

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


一开始我的想法是直接用2个for循环遍历nums,用当前数和当前数之后的所有数求和,如果和target相同就直接返回当前索引数组

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

但是这种算法时间复杂度是 O(n2),耗时很长,所以后来我参考了使用字典的方法:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap = {}
        for index, num in enumerate(nums):
            another_num = target - num
            if another_num in hashmap:
                return [hashmap[another_num], index]
            hashmap[num] = index
        return None

这种方法通过一个字典,遍历的时候将目标数字减去当前数字的值及索引插入,每次判断遍历的时候判断当前值是不是在字典中,在的话就将结果返回,非常高效。

 

  

Python版[leetcode]1. 两数之和(难度简单)

原文:https://www.cnblogs.com/davidlidvd/p/12247392.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!