题目
原文:
Design an algorithm to find all pairs of integers within an array which sum to a specified value.
译文:
设计一个算法找出数组中和为特定值的所有整型对。
解答
首先理解题意,题目条件给出一个特定值sum和一个数组,求出数组中满足两个数的和等于sum的所有整数对。可以先对数组进行增序排序,然后使用low和high 两个下标指向数组的首尾元素。如果a[low]+a[high] > sum,说明和偏大,则high--;若a[low]+a[high] < sum,说明和偏小,则low++;如果a[low]+a[high]等于sum, 则输出,并且进行low++和high--。当low小于high时,不断地重复上面的操作即可。
代码如下:
import java.util.*;
class Q19_11{
public static void main(String[] args){
int[] a={5,2,-4,9,4,3,8,6};
int sum=10;
printPairSum(a,sum);
}
public static void printPairSum(int[] a,int sum){
if(a==null||a.length<2) return;
Arrays.sort(a);
int low=0,high=a.length-1;
while(low<high){
if(a[low]+a[high]>sum){
high--;
}else if(a[low]+a[high]<sum){
low++;
}else{
System.out.println(a[low]+" "+a[high]);
low++;
high--;
}
}
}
}
---EOF---