Leetcode#167. Two Sum II - Input array is sorted

本文介绍了一种解决有序数组中寻找两个数使它们的和等于特定目标值的方法。通过利用数组已排序的特点,采用双指针技术高效地找到了目标值的组合方式,并详细解析了算法思路。

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

题目

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. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

题意

给出数字序列,找出目标值的组合方式对应的下标

想法

这道题一个比较重要的关键就是这个数字序列是排过序,搜索两个关键下标需要注意不能把正确值排除掉。容易想到的是如果a+d>targeta+d>target的话,对任意的b>ab>a的话均有b+d>=targetb+d>=target,没有缩小范围,我们会希望减少边界d。如果在更新后,a+d<targeta+d<target的话,对任意的c<dc<d,有a+c<targeta+c<target对搜索无用,希望能找到一个b会不会有可能和d配。
为什么最后的结果在这个搜索过程中没有被筛掉呢?因为对每一个小的数,都是从最小开始去试图从最大的方向往左找配对值,配对运算值比目标值大才会跳过改最大值为较小的较大值,前面也说过,跳过这个较大值是不会有影响的,因为较小值加上它都比目标大了,肯定没法配,直到比目标值小就会认为这个较小值已经没有可能配对成功了,而比较小值大的数也被证明过比当前的较大值后面的数没可能了,那自然就只能从当前的较大值开始配。如果定义配对值小的数叫A,大的数叫B,A把不能和比A大的数配对的大数筛掉了,B把不能和比B小的数配对的小数筛掉了。

class Solution:
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        index1, index2 = 0, len(numbers)-1
        while index1< index2:
            if numbers[index1] + numbers[index2] == target:
                return index1+1, index2+1
            elif numbers[index1] + numbers[index2] > target:
                index2-=1
            else:
                index1+=1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值