Daily question: Find two numbers in the array so that their sum is equal to a given target value.

Problem-solving ideas:

  1. Create an empty dictionary to store the index of each element in the array.
  2. Iterate over the array, for each element:
  • Computes the difference between the target value and the current element diff.
  • Check if it exists in the dictionary diff, if it exists, you have found two numbers that satisfy the condition.
  • If not present, the current element and its index are added to the dictionary.
  1. If no two numbers satisfying the condition are found, an empty list is returned.
  2. If two numbers satisfying the condition are found, their indices are returned.
def two_sum(nums, target):
    # 创建一个空字典,用于存储数组中每个元素的索引
    num_dict = {
    
    }
    
    # 遍历数组
    for i, num in enumerate(nums):
        # 计算目标值与当前元素的差值
        diff = target - num
        
        # 检查字典中是否存在差值
        if diff in num_dict:
            # 找到了满足条件的两个数,返回它们的索引
            return [num_dict[diff], i]
        
        # 将当前元素及其索引添加到字典中
        num_dict[num] = i
    
    # 没有找到满足条件的两个数,返回一个空列表
    return []

# 测试
nums = [2, 7, 11, 15]
target = 9
result = two_sum(nums, target)
print(result)  # 输出: [0, 1],因为 nums[0] + nums[1] = 2 + 7 = 9

The time complexity of this algorithm is O(n), where n is the length of the array. During the execution of the algorithm, we only need to traverse the array once, and for each element, the search operation can be performed in constant time. Therefore, the time complexity of this algorithm is linear.

Guess you like

Origin blog.csdn.net/qq_29669259/article/details/131591974