包阅导读总结
1.
关键词:Java 数组、接近零、迭代、流、排序
2.
总结:本文探讨了在 Java 数组中高效找出最接近零的数的多种技术,包括迭代、使用流和排序方法,优先考虑正数,给出了示例代码和详细解释。
3.
主要内容:
– 问题阐述
– 以包含正负数的数组为例,说明要找出最接近零的数,正数优先。
– 解决方案
– 迭代方法
– 遍历数组,通过比较绝对值和实际值来更新最接近零的数。
– 使用流(Java 8 及以上)
– 将数组元素装箱,使用自定义比较器找出最小值。
– 基于索引的迭代方法
– 迭代时维护最接近零的数的索引。
– 排序方法
– 对数组流进行自定义排序,获取第一个元素。
– 结论
– 总结探讨的找出 Java 数组中最接近零的数的多种技术。
思维导图:
文章地址: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.