给定一个长度为n的数组a[0],a[1]...a[n-1]和一个数字x,在数组中查找两个数a和b(可以是相同的值,但是不可以是相同位置的数字),使得它们的和与输入的数字差的绝对值最小。
比如:
a = [8,3,6,1] x=13
那么答案为:6和8
第一行两个数字 n,x(2<=n<=1000,1<=x<=108)第二行n个用空格隔开的数字a[0],a[1]...a[n-1]
两个数字a,b,用空格隔开。比较小的数字在左边,即输出要保证a<=b
4 13 8 3 6 1
6 8
import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.StringTokenizer; public class Main { static int[] array1; public static void main(String[] args) { //输入两个数 数组大小n 要比较的数x Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int x = sc.nextInt(); //数组array1 if (2 <= n && n <= 1000 && 1 <= x && x <= 10E8) { array1 = new int[n]; for (int i = 0; i < n; i++) { int b = sc.nextInt(); array1[i] = b; } //结果放进map Map map = new HashMap(); int c; int e=1000000; for (int i = 0; i < n; i++) { for (int j = 1; j < n; j++) { //去重 if (i == j || i > j) { continue; } c = Math.abs(array1[i] + array1[j]- x); map.put(c, Math.min(array1[i],array1[j]) + "," +Math.max(array1[i],array1[j]) ); e = Math.min(e, c); } } // System.err.println("最小绝对值"+e); StringTokenizer splitor = new StringTokenizer((String) map.get(e),","); while(splitor.hasMoreTokens()){ System.out.print(splitor.nextElement()+" "); } } } }