我正在嘗試解決以下問題:
給定五個正整數,找出可以通過將五個整數中的四個恰好相加來計算的最小值和最大值。然后將各自的最小值和最大值列印為單行的兩個空格分隔的長整數。
可以在下面看到的我的代碼能夠處理一些測驗用例,但其他一些我似乎無法弄清楚的失敗,問題似乎在于long max
賦值陳述句,并且可能與.sorted(Collections.reverseOrder())
組件有關,因為這是 min vs max 陳述句。
有效的示例測驗用例:
Input = [1, 2, 3, 4, 5]
Output = 10 (minimum), 14 (maximum)
不起作用的示例測驗用例:
Input = [256741038, 623958417, 467905213, 714532089, 938071625]
Output = 2063136757 (minimum), -1550499952 (maximum)
Expected Output = 2063136757 (minimum), 2744467344 (maximum)
class Result {
/*
* Complete the 'miniMaxSum' function below.
*
* The function accepts INTEGER_ARRAY arr as parameter.
*/
public static void miniMaxSum(List<Integer> arr) {
long max = arr.stream().sorted(Collections.reverseOrder()).limit(4).reduce(0, (subtotal, element) -> subtotal element);
long min = arr.stream().sorted().limit(4).reduce(0, (subtotal, element) -> subtotal element);
System.out.println(min " " max);
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s $", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
Result.miniMaxSum(arr);
bufferedReader.close();
}
}
uj5u.com熱心網友回復:
正如@Benjamin W. 所說,這里似乎發生了一些溢位。它可能與包含 Integer 物件而不是 long 的串列有關,但您必須進一步研究它。你的緩沖閱讀器看起來作業得很好。
如果你只是想要一個簡單的解決方案,你可以在串列中找到最小的數字,從最大的和中省略它,從串列中找到最大的元素,從最小的和中省略它。
public static void minmaxSum(List<Integer> arr) {
if (arr.size == 0) return;
long max = arr.get(0):
long min = arr.get(0);
long maxSum = 0;
long minSum = 0;
for (Integer num : arr) {
long longNum = (long) num.intValue();
maxSum = longNum;
minSum = longNum;
if (longNum < min) min = longNum;
if (longNum > max) max = longNum;
}
maxSum -= min;
minSum -= max;
System.out.println(minSum " " maxSum);
}
此外,這樣的代碼無論如何都要清晰得多。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/496069.html
上一篇:如何垂直回傳arraylist