问题:给定一个整型数组,是否能找出其中的两个数使其合为某个指定 的值?
思路:排序后,从数组两端向中间移动,一次移动一端的指针,直至两数合为为指定值。
java实现:
boolean hasSum(int[] A,int target) {
boolean res = false;
if (A == null || A.length < 2)
return res;
Arrays.sort(A);
int i = 0, j = A.length - 1;
while (i < j) {
if (A[i] + A[j] == target) {
res = true;
break;
} else if (A[i] + A[j] > target) {
j--;
} else {
i++;
}
}