返回

【Daily Interview】24 三数之和的优化与分析

前端

概述

三数之和问题是一个经典的面试题,也是 LeetCode 上的热门问题。给定一个整数数组和一个目标值,找出数组中三个元素的和等于目标值的组合。

算法

双指针法

双指针法是解决三数之和问题的一种常用方法。该方法使用两个指针从数组的两端开始,然后向中间移动。当两个指针相遇时,它们将指向数组中两个元素,其和等于目标值。

def three_sum(nums, target):
    """
    Finds all unique triplets in nums that sum to target.

    Args:
    nums: A list of integers.
    target: The target sum.

    Returns:
    A list of all unique triplets in nums that sum to target.
    """

    # Sort the array in ascending order.
    nums.sort()

    # Initialize two pointers.
    left = 0
    right = len(nums) - 1

    # While the left pointer is less than or equal to the right pointer.
    while left <= right:
        # Calculate the sum of the three elements.
        sum = nums[left] + nums[right] + nums[mid]

        # If the sum is equal to the target.
        if sum == target:
            # Add the triplet to the result list.
            result.append([nums[left], nums[mid], nums[right]])

            # Move the left pointer to the next element.
            left += 1

            # Move the right pointer to the previous element.
            right -= 1

        # If the sum is less than the target.
        elif sum < target:
            # Move the left pointer to the next element.
            left += 1

        # If the sum is greater than the target.
        else:
            # Move the right pointer to the previous element.
            right -= 1

    # Return the result list.
    return result

排序法

排序法是解决三数之和问题的一种简单方法。该方法将数组排序,然后使用三个指针从数组的开头、中间和结尾开始。当三个指针相遇时,它们将指向数组中三个元素,其和等于目标值。

def three_sum(nums, target):
    """
    Finds all unique triplets in nums that sum to target.

    Args:
    nums: A list of integers.
    target: The target sum.

    Returns:
    A list of all unique triplets in nums that sum to target.
    """

    # Sort the array in ascending order.
    nums.sort()

    # Initialize three pointers.
    left = 0
    mid = 1
    right = len(nums) - 1

    # While the left pointer is less than or equal to the right pointer.
    while left <= right:
        # Calculate the sum of the three elements.
        sum = nums[left] + nums[mid] + nums[right]

        # If the sum is equal to the target.
        if sum == target:
            # Add the triplet to the result list.
            result.append([nums[left], nums[mid], nums[right]])

            # Move the left pointer to the next element.
            left += 1

            # Move the mid pointer to the next element.
            mid += 1

        # If the sum is less than the target.
        elif sum < target:
            # Move the left pointer to the next element.
            left += 1

        # If the sum is greater than the target.
        else:
            # Move the right pointer to the previous element.
            right -= 1

    # Return the result list.
    return result

哈希表法

哈希表法是解决三数之和问题的一种快速方法。该方法将数组中的元素存储在一个哈希表中,然后使用两个指针从数组的开头和结尾开始。当两个指针相遇时,它们将指向数组中两个元素,其和等于目标值。

def three_sum(nums, target):
    """
    Finds all unique triplets in nums that sum to target.

    Args:
    nums: A list of integers.
    target: The target sum.

    Returns:
    A list of all unique triplets in nums that sum to target.
    """

    # Create a hash table to store the elements in the array.
    hash_table = {}

    # Iterate over the array and store each element in the hash table.
    for num in nums:
        hash_table[num] = True

    # Initialize two pointers.
    left = 0
    right = len(nums) - 1

    # While the left pointer is less than or equal to the right pointer.
    while left <= right:
        # Calculate the complement of the target sum.
        complement = target - nums[left] - nums[right]

        # If the complement is in the hash table.
        if complement in hash_table:
            # Add the triplet to the result list.
            result.append([nums[left], nums[right], complement])

            # Move the left pointer to the next element.
            left += 1

            # Move the right pointer to the previous element.
            right -= 1

        # If the complement is not in the hash table.
        else:
            # Move the left pointer to the next element.
            left += 1

    # Return the result list.
    return result

时间复杂度

双指针法和排序法的