[leetcode刷题(easy)]之一: 两数之和

题目描述

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

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

示例:

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

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

解题代码

1、暴力法:遍历每一个元素,时间复杂度:O(n^{2}),空间复杂度:O(1).,用时52ms

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        t_list = []
        l_nums = len(nums)
        for i in range(0,l_nums):
            for j in range(i+1, l_nums):
                if nums[i] + nums[j] == target:
                    t_list.append(i)
                    t_list.append(j)
                    return t_list

2、两遍哈希表

一种更有效的方法来查找数组中是否存在目标元素。

使用两次迭代,在第一次迭代中,我们将每个元素的值和它的索引添加到表中(python中数据结构为字典)。然后,在第二次迭代中,我们将检查每个元素所对应的目标元素(target - nums[i]target−nums[i])是否存在于表中。注意,该目标元素不能是 nums[i]nums[i] 本身!

时间复杂度:O(n),空间复杂度(n),执行时间32ms。

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if not nums:
            return None
            
        d = {}
        for i, item in enumerate(nums):
            tmp  = target - item
            
            for key, value in d.items():
                if value == tmp:
                    return [key, i]
            
            d[i] = item
            
        return None

3、一遍哈希表

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if not nums:
            return None
        
        d = {}
        for i, item in enumerate(nums):
            temp = target - item
            if temp in d:
                return [d[temp], i]
            d[item] = i
        
        return None

猜你喜欢

转载自blog.csdn.net/weixin_41931548/article/details/88988144
今日推荐