代码实现:
import java.util.Arrays;
/**
* 使用双指针实现两数之和
*/
public class TwoNumSum {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5,6};
//返回位置的信息
System.out.println(Arrays.toString(twoPoint(arr, 8)));
}
public static int[] twoPoint(int[] numbers,int target){
int low =0;
int high = numbers.length-1;
while (low < high){
int sum = numbers[low] + numbers[high];
if (sum == target){
return new int[]{low,high};
} else if (sum < target || sum == target){
low++;
}else {
high--;
}
}
return new int[]{0};
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)