返回

LeetCode 1. 两数之和:轻松掌握双指针算法,探索数组奥秘!

前端

LeetCode 1. 两数之和:踏上算法之旅

[路飞]_leetcode,欢迎来到算法之旅的起点!LeetCode 1. 两数之和,一个经典的算法问题,将为你揭开算法世界的大门。准备好接受挑战了吗?

算法精粹:双指针算法

LeetCode 1. 两数之和的灵魂在于双指针算法,一种高效且优雅的算法。我们将使用两个指针,从数组的两端开始向中间移动,不断检查它们的和是否等于目标值。如果相等,我们就找到了答案!否则,我们就调整指针的位置,继续寻找。

Python代码实现:清晰易懂,一学就会

def twoSum(nums, target):
  """
  :type nums: List[int]
  :type target: int
  :rtype: List[int]
  """
  # Initialize two pointers
  left, right = 0, len(nums) - 1

  # While the pointers have not crossed each other
  while left < right:
    # Calculate the sum of the current elements pointed by the two pointers
    sum = nums[left] + nums[right]

    # Check if the sum is equal to the target
    if sum == target:
      # Return the indices of the two elements
      return [left, right]

    # If the sum is less than the target, move the left pointer to the right
    elif sum < target:
      left += 1

    # If the sum is greater than the target, move the right pointer to the left
    else:
      right -= 1

  # Return an empty list if no solution is found
  return []

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.count(complement)) {
      return {seen[complement], i};
    }
    seen[nums[i]] = i;
  }
  return {};
}

Java代码实现:面向对象,优雅清晰

import java.util.HashMap;

class Solution {
    /**
     * Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
     * You may assume that each input would have exactly one solution, and you may not use the same element twice.
     *
     * @param nums   The array of integers to search.
     * @param target The target sum.
     * @return The indices of the two numbers that add up to target, or an empty array if no such solution exists.
     */
    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];
    }
}

结语

LeetCode 1. 两数之和只是算法之旅的起点,前方还有更多精彩的挑战等着你。继续探索,你会发现算法世界的魅力无穷!