Python版[leetcode]1. 两数之和(难度简单),,给定一个整数数组 n


给定一个整数数组 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. 两数之和(难度简单)

评论关闭