(Leetcode) 两数之和 II - 输入有序数组 - Python实现

本文详细解析了LeetCode经典题目“两数之和II”的多种解法,包括双循环、字典索引、二分查找和双指针法,对比了不同算法的时间和空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:两数之和 II - 输入有序数组

给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9. 输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。

---------------------------------------------------------------

错误解法0:利用有序列表这一条件,直接在 numbers[i+1:] 查找 差值结果。

无法处理类似,numbers = [0,0,1,5], target = 0 这种同时存在两个相同数字的要求。

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """

        n = len(numbers)
        for i in range(len(numbers)):
            dif = target - numbers[i]
            
            if dif in numbers[i+1:]:
                return [i+1, numbers.index(dif)+1]

        return []

解法1:最直白的笨办法,双循环。时间复杂度:O(n^2),超时!!!

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
  
        n = len(numbers)
        for i in range(n-1):
            for j in range(i+1, n):
                if numbers[i] + numbers[j] == target:
                    return [i+1, j+1]
        return []

解法2:通过字典建立索引列表,将每个差值和对应下标,保存在字典列表中,然后同时输出。 时间复杂度:O(n)。

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """

        dic = {}
        li = []
        for i in range(len(numbers)):
            if numbers[i] in dic.keys():

                # 将原始值和差值的下标分别添加到li中
                li.append(dic[numbers[i]]+1)   # 原始值的下标
                li.append(i+1)  # 差值的下标
                return li

            # 将每个值的差值及对应的下标, 保存在字典中
            dic[target-numbers[i]] = i

        return None

 

解法3:二分法查找差值的下标。时间复杂度:O(nlogn)。

class Solution(object):
    def BiSearch(self, numbers, target):
        # 通过二分法寻找每个差值的下标mid
        left = 0
        right = len(numbers)-1
        while left <= right:
            mid = (left + right) // 2
            if target == numbers[mid]:
                return mid
            elif target < numbers[mid]:
                right = mid - 1
            else:
                left = mid + 1
        return -1

    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        nums_len = len(numbers)
        for i in range(nums_len):
            dif = target-numbers[i]
            # 在numbers[i+1:]中获取差值下标
            dif_index = self.BiSearch(numbers[i+1:], dif)
            if dif_index != -1:
                return [i + 1, dif_index + i + 2]
        return []

 

解法4:对撞指针法(双索引法)。空间复杂度:O(1),时间复杂度:O(n)。

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """

        left = 0  # 左指针
        right = len(numbers)-1  # 右指针

        # 始终保证左指针的下标小于右指针
        while left < right:
            # print(left, right)
            if numbers[left] + numbers[right] == target:
                return [left+1, right+1]
            # 当二者之和小于目标值, 让左指针右移一位, 换一个更大的值
            elif numbers[left] + numbers[right] < target:
                left += 1
            # 当二者之和大于目标值, 让右指针左移一位, 换一个更小的值
            else:
                right -=1
        return []

 

参考:

https://blog.youkuaiyun.com/qq_34364995/article/details/80518200

https://blog.youkuaiyun.com/qq_17550379/article/details/80512745

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值