方法一:用HashMap< Integer, Integer> map,一次遍历,判断map中是否存在x-a[i],存在则直接返回 a[i] 和x-a[i],否则将a[i]加入map。
方法二:排序后,从首尾出发,判断其和
public static void main(String[] args) {
int a[] = { 1, 2, 2, 4,4, 5, 7, 11, 15 };
useHashmap(a, 15);
System.out.println("------------");
useTwoPointer(a, 15);
}
private static void useHashmap(int a[], int x) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < a.length; i++) {
if( !map.containsKey( a[i])) //添加
map.put( a[i], 1);
else map.put( a[i], map.get(a[i])+1);
if (map.containsKey(x - a[i])) //符合条件
if( map.get( x-a[i])>1) {
for( int j=map.get( x-a[i]); j>0; j--)
System.out.println( a[i] + "," + (x-a[i]));
map.put( x-a[i], 1);
}
else System.out.println( a[i] + "," + (x-a[i]));
}
}
private static void useTwoPointer(int a[], int x) {
Arrays.sort(a);
int i = 0, j = a.length - 1;
while (i < j) {
if (a[i] + a[j] == x) {
System.out.println(a[i] + "," + a[j]);
if (a[i + 1] + a[j] == x && i + 1 < j)
i++;
else if (a[i] + a[j - 1] == x && i < j - 1)
j--;
else
i++;
}
else if (a[i] + a[j] < x)
i++;
else
j--;
}
}
结果截图: