LeetCode 1. Two Sum(Python)

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

1. 暴力破解法

暴力法很简单。遍历每个元素 x,并查找是否存在一个值与 target−x 相等的目标元素。 

# 暴力破解法
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            cha = target - nums[i]
            for j in range(i+1, len(nums)):
                if nums[j] == cha:
                    return [i, j]
  • 时间复杂度:O(n^2), 对于每个元素,我们试图通过遍历数组的其余部分来寻找它所对应的目标元素,每一次耗费O(n) 的时间。总共的时间复杂度为 O(n^2)

  • 空间复杂度:O(1)

2.遍历两遍字典

为了对运行时间复杂度进行优化,我们需要一种更有效的方法来检查数组中是否存在目标元素。如果存在,我们需要找出它的索引。保持数组中的每个元素与其索引相互对应的最好方法是使用字典。

扫描二维码关注公众号,回复: 5721927 查看本文章

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

# 两遍字典
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        map = {}
        for i in range(len(nums)):
            map[nums[i]] = i
        
        for i in range(len(nums)):
            complement = target - nums[i]
            if map.__contains__(complement) and map[complement] != i:
                return [i, map[complement]]
  • 时间复杂度:O(n), 我们把包含有 n 个元素的列表遍历两次。由于字典将查找时间缩短到 O(1) ,所以时间复杂度为 O(n)。

  • 空间复杂度:O(n), 所需的额外空间取决于字典中存储的元素数量,该字典最多需要存储 n个元素。

3.遍历一遍字典

在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。

# 一遍字典
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        map = {}
        for i in range(len(nums)):
            complement = target - nums[i]
            
            if map.__contains__(complement) and map[complement] != i:
                return [map[complement], i]
        
        map[nums[i]] = i 
        
  • 时间复杂度:O(n), 我们只遍历了包含有 n个元素的列表一次。在字典中进行的每次查找只花费 O(1)的时间。

  • 空间复杂度:O(n), 所需的额外空间取决于字典中存储的元素数量,该字典最多需要存储 n个元素。

猜你喜欢

转载自blog.csdn.net/HNU_Csee_wjw/article/details/88903593