返回

<如何在 LeetCode 上解决「两数之和」问题? - 从算法思维到编程实现>

前端

「两数之和」的算法奥秘:从概念到实践

算法思维:庖丁解牛

当我们面对「两数之和」这一经典算法问题时,与其仓促求解,不如先抽丝剥茧,层层深入地理解其算法思维。问题的本质在于,我们需要在给定数组中找出两数之和等于指定目标值的索引对。为此,我们可以将其分解为以下几个步骤:

  1. 遍历数组: 从第一个元素开始,依次遍历整个数组中的每一个元素。

  2. 比较元素: 对于每个元素,将其与之前遍历过的所有元素进行比较,检查是否存在一对元素之和等于指定的目标值。

  3. 存储索引: 如果找到满足条件的元素对,将它们的索引存储起来。

编程实现:代码千行,殊途同归

理解了算法思维后,我们就可以着手编写代码了。虽然不同的编程语言语法各异,但算法的核心思想却是一致的。以下是用 Python、Java、C++ 和 JavaScript 实现「两数之和」算法的代码示例:

Python

def two_sum(nums, target):
    """
    Finds the indices of two numbers in a list that sum to a target value.

    Args:
    nums: A list of numbers.
    target: The target value to find the sum of.

    Returns:
    A list of two indices that sum to the target value, or an empty list if no such pair exists.
    """

    # Create a dictionary to store the indices of the numbers we have seen so far.
    seen = {}

    # Iterate over the list of numbers.
    for i, num in enumerate(nums):
        # Calculate the complement of the target value.
        complement = target - num

        # Check if the complement is in the dictionary.
        if complement in seen:
            # Return the indices of the two numbers that sum to the target value.
            return [seen[complement], i]

        # Add the current number and its index to the dictionary.
        seen[num] = i

    # No pair of numbers sums to the target value.
    return []

Java

public class TwoSum {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> seen = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];

            if (seen.containsKey(complement)) {
                return new int[] { seen.get(complement), i };
            }

            seen.put(nums[i], i);
        }

        return new int[0];
    }
}

C++

vector<int> twoSum(vector<int>& nums, int target) {
  unordered_map<int, int> seen;

  for (int i = 0; i < nums.size(); i++) {
    int complement = target - nums[i];

    if (seen.find(complement) != seen.end()) {
      return {seen[complement], i};
    }

    seen[nums[i]] = i;
  }

  return {};
}

JavaScript

const twoSum = (nums, target) => {
  const seen = {};

  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];

    if (seen[complement] !== undefined) {
      return [seen[complement], i];
    }

    seen[nums[i]] = i;
  }

  return [];
};

总结:殊途同归的算法奥秘

通过剖析「两数之和」问题的算法思维并编写代码,我们领略了算法的通用性。无论您使用哪种编程语言,算法的本质都是相同的。希望这篇文章能帮助您提升算法能力和编程技巧。

常见问题解答

  1. 什么是「两数之和」问题?

「两数之和」问题是找出给定数组中两数之和等于指定目标值的索引对。

  1. 如何解决「两数之和」问题?

可以使用哈希表来存储已遍历元素及其索引,然后遍历数组,并检查目标值和当前元素之差是否在哈希表中。

  1. 「两数之和」问题的时间复杂度是多少?

使用哈希表实现的「两数之和」问题的时间复杂度为 O(n),其中 n 是数组的长度。

  1. 如何优化「两数之和」算法?

可以对数组进行排序,然后使用双指针法来遍历数组。这样可以将时间复杂度降低到 O(n log n)。

  1. 「两数之和」问题在实际场景中的应用有哪些?

「两数之和」问题在实际场景中有着广泛的应用,例如:

  • 检查交易记录中是否存在可疑交易(两笔交易之和等于某个特定金额)
  • 计算购物篮中的商品总金额
  • 查找两个字符串中的相同子字符串