167. 两数之和 II - 输入有序数组

给你一个下标从 1 开始的整数数组 numbers ,该数组已按 非递减顺序排列 ,请你从数组中找出满足相加之和等于目标数 target 的两个数。如果设这两个数分别是 numbers[index1]numbers[index2] ,则 1 <= index1 < index2 <= numbers.length

以长度为 2 的整数数组 [index1, index2] 的形式返回这两个整数的下标 index1index2

你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。

你所设计的解决方案必须只使用常量级的额外空间。

思路

  • 双指针
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.wereash.scut_hot100;

import java.util.Scanner;

/**
* @Author: WereAsh
* @Date:2026-01-22 19:15
**/
public class Solution167 {
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
String[] str=scanner.nextLine().split(",");
int target=scanner.nextInt();
int[] nums=new int[str.length];
for (int i=0;i<str.length;i++){
nums[i]=Integer.parseInt(str[i]);
}
int left=0,right=nums.length-1;
while(left<right){
int temp=nums[left];
int rest=target-temp;
while (left<right&&nums[right]>rest) right--;
if(left<right&&nums[right]==rest){
System.out.println("["+left+","+right+"]");
return;
}
left++;
}
System.out.println("无解");
}
}