其他分享
首页 > 其他分享> > LeetCode刷题9-两数之和绝对值最小

LeetCode刷题9-两数之和绝对值最小

作者:互联网

package com.example.demo.leetcode.case202208;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能描述
 *
 * @author ASUS
 * @version 1.0
 * @Date 2022/8/6
 */
public class Main2022080603 {
    /*
        标题:
        两数之和绝对值最小
        给定一个从小到大的有序整数序列(存在正整数和负整数)数组 nums,请你在该数组中找出两个数,其和的绝对值(|nums[x]+nums[y]|)为 最小值,并返回 这个绝对值。
        每种输入只会对一个答案。但是,数组中同一个元素不能使用两遍。
        输入描述:
        一个通过空格分割的有序整数序列字符串,最多 1000个整数,且整数数值范围是-65535~65535。
        输出描述:
        两数之和绝对值最小值。
        示例:
        输入
        -3 -1 5 7 11 15
        输出
        2
    */
    public static void main(String[] args) {
        // 获取输入的数据
        Scanner scanner = new Scanner(System.in);
        List<Integer> list = Arrays.stream(scanner.nextLine().split(" ")).map(s -> Integer.parseInt(s)).collect(Collectors.toList());

        // 绝对值最小数 初始化为最大值
        int min = Integer.MAX_VALUE;
        int value1 = 0;
        int value2 = 0;
        for (int i = 0; i < list.size(); i++) {
            for (int j = i + 1; j < list.size(); j++) {
                // 两两求和 取绝对值
                int abs = Math.abs(Math.addExact(list.get(i), list.get(j)));
                // 保存最小的值
                if (abs <= min) {
                    // 本题因前提只有一种答案 如一个最小绝对值对应多组数据需要优化写法  判断条件abs == min
                    // List<String> newList = new LinkedList<String>(); newList.removeAll(newList);
                    min = abs;
                    value1 = list.get(i);
                    value2 = list.get(j);
                }
            }
        }

        // 打印
        System.out.println(value1 + " " + value2 + " " + min);
    }
}

 

标签:get,int,list,abs,绝对值,LeetCode,两数,刷题
来源: https://www.cnblogs.com/chch213/p/16557365.html