1、题目描述
输入一个递增排序的数组array和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,返回任意一组即可,如果无法找出这样的数字,返回一个空数组即可。
数据范围:
0<=len(array)<=105
1<=array[i]<=106
2、算法分析
先说下双指针法:
无论是数组中还是链表中,双指针的应用都非常高效。
双指针就是有两个index。至于本题,因为数组是一个递增的数组,只需要第一个指针指向数组的0index,第二个指针指向数组的length-1结点。
首先数组首尾元素进行相加,和sum的值进行比较。
如果sum的值大于array[start]+array[end],那么end--,缩小array[start]+array[end];
如果sum的值小于array[start]+array[end],那么start++,扩大array[start]+array[end];
如果sum == array[start]+array[end],将array[start] ,array[end]添加到集合ArrayList里面。
返回集合对象。
3、代码实现
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
ArrayList<Integer> result = new ArrayList<>();
if(array == null || array.length == 0){
return result;
}
int start = 0;
int end = array.length - 1;
while(start < end){
if((array[start] + array[end]) > sum){
end--;
}else if((array[start] + array[end]) < sum){
start++;
}else if(array[start] + array[end] == sum){
result.add(array[start]);
result.add(array[end]);
return result;
}
}
return result;
}
}