twoSum II - Leet Code -运行时错误-超出限制



问题:twoSum给定一个已按非递减顺序排序的整数数组,找出两个数字,使它们之和等于一个特定的目标数。

返回两个数字(以1为索引)的索引作为大小为2的整数数组答案,其中1 <= answer[0] <答案[1]><= numbers.length.

生成的测试只存在一个解决方案。同一个元素不能重复使用。

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

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

int a_pointer = 0;
int b_pointer = numbers.length - 1;

while (a_pointer < b_pointer) {
int sum=numbers[a_pointer] + numbers[b_pointer];

if (sum > target) {
b_pointer-=1;
} else if (sum < target) {
b_pointer+=1;
} else {
return new int[] {a_pointer+1, b_pointer+1};
}           
}
throw new IllegalArgumentException("no match found");
}
};

错误:

java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at line 8, Solution.twoSum
at line 54, __DriverSolution__.__helper__
at line 87, __Driver__.main

运行测试用例

[5,25,75]
100

在您的代码中,您在一个条件中增加了b_pointer的值,因此它成为数组的大小(因为您将其初始化为arr)。长度- 1)

else if (sum < target) {
b_pointer+=1;
} 

最新更新