Posted in

如何在 Java 数组中找到最接近零的数字_AI阅读总结 — 包阅AI

包阅导读总结

1. `Java 数组`、`最接近零`、`迭代`、`流`、`排序`

2. 本文探讨了在 Java 数组中高效找出最接近零的数的多种技术,包括迭代、使用流、基于索引的迭代、排序等方法,并通过示例代码进行了演示,以解决在不同场景中查找最接近给定目标值的问题。

3.

– 问题阐述

– 以包含正整数和负整数的数组为例,说明需找出最接近零且正整数优先的数。

– 解决方法

– 迭代方法

– 初始化最接近零的数为数组首元素,遍历比较更新。

– 使用流(Java 8 及以上)

– 将数组元素装箱为整数对象,通过自定义比较器找出最小值。

– 基于索引的迭代方法

– 维护最接近零数的索引,比较绝对差值和正负情况更新。

– 排序方法

– 对数组元素装箱排序,获取第一个元素。

– 结论

– 探索了多种有效找出最接近零的数的技术。

思维导图:

文章地址:https://www.javacodegeeks.com/how-to-find-the-closest-number-to-zero-in-java-arrays.html

文章来源:javacodegeeks.com

作者:Omozegie Aziegbe

发布时间:2024/7/26 15:20

语言:英文

总字数:808字

预计阅读时间:4分钟

评分:84分

标签:Java,数组处理,算法,Java 8 Streams,排序


以下为原文内容

本内容来源于用户推荐转载,旨在分享知识与观点,如有侵权请联系删除 联系邮箱 media@ilingban.com

This article explores several techniques to efficiently find the closest number to zero in a Java array with positive integers taking priority over negative ones. This problem can arise in various scenarios, such as when working with temperature data, financial calculations, or any dataset that requires finding the nearest value to a given target.

1. Example to Illustrate the Problem

Suppose we have the following array:

int[] data = {2, 3, -2, 4, -5};

The closest numbers to zero in this array are 2 and -2. Since positive integers take priority, the answer should be 2.

2. Iterative Approach

This method involves iterating through the array and keeping track of the closest number to zero.

public class ClosestToZero {    public static int findClosestToZero(int[] numbers) {        if (numbers == null || numbers.length == 0) {            throw new IllegalArgumentException("Array must not be null or empty");        }        int closest = numbers[0];        for (int number : numbers) {            if (Math.abs(number) < Math.abs(closest) ||                (Math.abs(number) == Math.abs(closest) && number > closest)) {                closest = number;            }        }        return closest;    }    public static void main(String[] args) {        int[] data = {2, 3, -2, 4, -5};        System.out.println("Closest number to zero: " + findClosestToZero(data));    }}

We start by setting the initial value of closest to the first element of the array. Then, we iterate through each number in the array. For each number, we compare its absolute value to the absolute value of closest. If the current number is closer to zero or equally close but positive, we update the value of closest.

3. Using Streams (Java 8 and above)

Java 8 streams provide a declarative approach to processing sequences of elements.

public class StreamClosestToZero {    public static int findClosestToZero(int[] numbers) {        return Arrays.stream(numbers)                     .boxed()                     .min((a, b) -> {                         int cmp = Integer.compare(Math.abs(a), Math.abs(b));                         if (cmp != 0) return cmp;                         return Integer.compare(b, a);                     })                     .orElseThrow(() -> new IllegalArgumentException("Array must not be empty"));    }    public static void main(String[] args) {        int[] data = {2, 3, -2, 4, -5};        System.out.println("Closest number to zero: " + findClosestToZero(data));    }}

We use Arrays.stream to create a stream from the array. The primitive int elements are boxed into Integer objects. The min method is then used with a custom comparator that first compares the absolute values of the elements. If the absolute values are equal, the comparator prefers positive numbers by comparing the actual values.

4. Index-Based Iterative Approach

This method involves iterating through the array, keeping track of the closest number to zero by maintaining the index of this number. This approach also ensures that positive numbers take priority over negative ones if both are equally close to zero.

public class IndexBasedClosestToZero {    public static void main(String[] args) {        int[] arr = {2, 3, -2, 4, -5, 1};        int closestIndex = 0;        int minDiff = Integer.MAX_VALUE;        for (int i = 0; i < arr.length; ++i) {            int absValue = Math.abs(arr[i]);            if (absValue < minDiff) {                closestIndex = i;                minDiff = absValue;            } else if (absValue == minDiff && arr[i] > 0 && arr[closestIndex] < 0) {                closestIndex = i;            }        }        System.out.println("Closest number to zero: " + arr[closestIndex]);    }}

We begin by setting closestIndex to the first index of the array and minDiff to the maximum possible integer value. We then iterate through each element in the array, calculating the absolute value of each element. If this absolute value is smaller than minDiff, we update closestIndex to the current index and minDiff to this absolute value.

If the absolute value is equal to minDiff but the current element is positive and the element at closestIndex is negative, we update closestIndex to the current index. After completing the iteration, the element at closestIndex is the closest number to zero.

5. Sorting

This approach sorts the array based on the criteria and then picks the first element.

public class SortingClosestToZero {    public static int findClosestToZero(int[] numbers) {        return Arrays.stream(numbers)                .boxed()                .sorted((a, b) -> {                    int cmp = Integer.compare(Math.abs(a), Math.abs(b));                    if (cmp != 0) {                        return cmp;                    }                    return Integer.compare(b, a);                })                .findFirst()                .orElseThrow(() -> new IllegalArgumentException("Array must not be empty"));    }    public static void main(String[] args) {        int[] data = {2, 3, -2, 4, -5, 1};        System.out.println("Closest number to zero: " + findClosestToZero(data));    }}

Similar to the stream method, we utilize Arrays.stream and box the elements into Integer objects. We then sort the stream using a custom comparator. Finally, we use findFirst to retrieve the first element of the sorted stream, which is the closest to zero.

6. Conclusion

In this article, we explored several techniques to efficiently find the closest number to zero in a Java array. We covered the iterative approach, the use of Java streams, and the sorting approach.

6. Download the Source Code