在一个数组中使用仅 1 个流来寻找一对元素的最大差异

huangapple go评论88阅读模式
英文:

Finding maximum difference of pair of elements in an array using EXACTLY 1 stream

问题

我正在尝试编写一个函数,以找到数组(1D)中任意两个元素之间的最大差异。我已经用几种方法解决了这个问题(我在Java中应用)

  1. 通过2个嵌套循环(有效,找到差值并取最大值)
  2. 通过1次循环迭代(有效,在返回最小值和最大值之后返回它们的差值:(最大值 - 最小值))
  3. 使用两次流处理(有效,使用流的min()和max()函数找到最大值和最小值,然后返回它们的差值)。

现在的问题是:如何编写一个使用仅一个流处理来计算数组中任意两个元素之间的最大差异的函数?

以下是我最后编写的一个函数:

public static int maxDifference(int[] arr) {
    return Arrays.stream(arr).min().orElseThrow(NoSuchElementException::new) -
           Arrays.stream(arr).max().orElseThrow(NoSuchElementException::new);
}
英文:

I am trying to write a function to find maximum difference between any 2 elements in an array (1D). I have already solved it in several ways (I apply in Java)

  1. With 2 nested loops (works, finds difference and takes the maximum)
  2. With 1 loop iteration (works, finds minimum and maximum after returns difference of them: (max - min))
  3. Using stream twice (works, finds maximum and minimum with stream's min() and max() functions and return difference).

Now the question is: How to write a function which calculate maximum difference between any 2 elements in an array using exactly 1 stream?

Here is the last one I wrote:

public static int maxDifference(int[] arr) {
    return Arrays.stream(arr).min().orElseThrow(NoSuchElementException::new) -
           Arrays.stream(arr).max().orElseThrow(NoSuchElementException::new);
}

答案1

得分: 5

使用 Arrays.stream(arr).summaryStatistics() - 它会返回一个 IntSummaryStatistics 对象,该对象具有用于获取最小值和最大值的访问器。

英文:

Use Arrays.stream(arr).summaryStatistics() - it returns you an IntSummaryStatistics object which has accessors for min and max.

huangapple
  • 本文由 发表于 2020年4月10日 03:15:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/61128611.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定