問題:給定一個整型數組,是否能找出其中的兩個數使其合爲某個指定 的值?
思路:排序後,從數組兩端向中間移動,一次移動一端的指針,直至兩數合爲爲指定值。
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++;
}
}