前言
《华为OD笔试真题 JAVA》 专栏含华为OD机试真题JAVA实现、华为面试题、牛客网华为专栏真题。
如果您正在准备华为的面试,或者华为od的机会,希望可以帮到您! PS:文中答案仅供参考,不可照抄
■ 题目描述
【乱序整数序列两数之和绝对值最小】
给定一个随机的整数(可能存在正整数和负整数)数组 nums,请你在该数组中找出两个数,其和的绝对值(|nums[x]+nums[y]|)为最小值,并返回这个两个数(按从小到大返回)以及绝对值。
每种输入只会对应一个答案。
但是,数组中同一个元素不能使用两遍。
输入描述
一个通过空格分割的有序整数序列字符串,最多1000个整数,且整数数值范围是 [-65535, 65535]。
输出描述
两数之和绝对值最小值
示例1 输入输出示例仅供调试,后台判题数据一般不包含示例
输入
-1 -3 7 5 11 15
输出
-3 5 2
说明
因为 |nums[0] + nums[2]| = |-3 + 5| = 2 最小,所以返回 -3 5 2。
JAVA代码实现:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
public class TwoSumAbs {
public static void main(String[] args) {
int total = 65535 * 2;
int[] index = new int[2];
Scanner sc = new Scanner(System.in);
String dataList = sc.nextLine();
String[] strArr = dataList.split(" ");
ArrayList<Integer> dataNewList = new ArrayList<>();
for (String s : strArr) {
dataNewList.add(Integer.valueOf(s));
}
dataNewList.sort(Comparator.naturalOrder());
for (int i = 0; i < dataNewList.size(); i++) {
for (int j = i + 1; j < dataNewList.size(); j++) {
int temp = Math.abs(dataNewList.get(i) + dataNewList.get(j));
if (temp <= total) {
total = temp;
index[0] = i;
index[1] = j;
}
}
}
System.out.println(dataNewList.get(index[0]) + " "
+ dataNewList.get(index[1]) + " " + total);
}
}