leetcode-167 Two Sum II-Input array is sorted

本文介绍了一种解决有序数组中寻找两个数使其和等于特定目标值的问题的方法。通过使用双指针技巧,从前和从后同时遍历数组,有效地找到满足条件的两个数的下标,提供了一个简洁高效的解决方案。

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.

Note:

  • 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.

    Example:

    Input: numbers = [2,7,11,15], target = 9
    Output: [1,2]
    Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1

中文大意:

给定一个已按升序排序的整数数组,找到两个数字,使它们相加得到一个特定的目标数字。函数two和应该返回两个数字的指标,使它们相加得到目标值,其中index1必须小于index2。

注记:您返回的答案(index1和index2)不是基于零的。您可以假设每个输入都只有一个解决方案,并且可能不会两次使用相同的元素。

解题思路:

一个数组,取两个值相加得到target,由于这个数组它的顺序是有序的,所以分别去前面的值与后面的值进行相加,当得到result结果时,我们可以返回一个result数组值,即返回最后的结果

代码如下

class Solution {
public int[] twoSum(int[] numbers, int target) {

//最后的返回的数组,记录结果数组由那两个位置的值进行相加的到
int[] result=new int[2];

//前向的标记
int count1=0;

//后向的标记
int count2=numbers.length-1;

//依次遍历数组
while(count1<count2)
{

//得到result时,返回两个结果位置
if(numbers[count1]+numbers[count2]==target)
{
result[0]=count1+1;
result[1]=count2+1;
break;
}

//结果大于target时,将后面的count2向前移
else if(numbers[count1]+numbers[count2]>target)
{
count2--;
}

//结果小于target时,将前面的count1向后移
else{
count1++;
}
}
return result;
}
}

 

转载于:https://www.cnblogs.com/longlyseul/p/9838578.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值