我有一个由int []数组组成的数组列表,我试图找到具有最低max元素的数组。
例如,从数组[1,2,5],[0,1,2],[8,0,0]中,它将是数组[0,1,2],因为最大元素为2
但是,我的代码无法正常工作。您能帮我修复我的代码吗?谢谢!
int min = Integer.MAX_VALUE;
for (int i=0; i<list.size(); i++) {
for (int j=0; j<list.get(i).length; j++) {
if (list.get(i)[j]<min) {
min = list.get(i)[i];
minIndex = i; //index of the array in arraylist
}
}
}
答案 0 :(得分:2)
您的代码找到了所有数组中的最小值(至少将list.get(i)[i]
的错字固定为list.get(i)[j]
时才发现)。
您应该找到每个数组的最大值,然后检查该最大值是否小于以前找到的所有最大值:
int minIndex = 0;
int min = Integer.MAX_VALUE;
for (int i=0; i<list.size(); i++) {
int max = Integer.MIN_VALUE;
for (int j=0; j<list.get(i).length; j++) { // find max element of current array
if (list.get(i)[j] > max) {
max = list.get(i)[j];
if (max > min) {
break; // we already know the max of this array is not the smallest max
}
}
}
if (max < min) { // check if the max of the current array is the smallest max so far
min = max;
minIndex = i; //index of the array in arraylist
}
}
答案 1 :(得分:0)
您可以尝试以下操作:
import java.util.Arrays;
import java.util.Comparator;
public class MaxMinArray {
public static int[] maxMinFromArray(int[][] arrays){
return Arrays.stream(arrays).min(Comparator.comparingInt(x -> Arrays.stream(x).max().orElse(0))).orElse(null);
}
}
我已经用您的示例对其进行了测试:):
import org.junit.Test;
import static org.junit.Assert.*;
public class MaxMinArrayTest {
@Test
public void testMaxMinArray(){
int[][] arrays = new int[][] {{1,2,5}, {0,1,2}, {8,0,0}};
int[] result = MaxMinArray.maxMinFromArray(arrays);
assertArrayEquals(new int[]{0,1,2}, result);
}
}
答案 2 :(得分:0)
作为for循环的替代方法,您可以尝试使用stream api解决此问题。这个想法是完全一样的:
List.of(List.of(1, 2, 5), List.of(0, 1, 2), List.of(8, 0, 0))
.stream()
.min((a, b) ->
a.stream().max(Integer::compare).get()
.compareTo(
b.stream().max(Integer::compare).get()
)
).get();
代码少了,可以很容易地理解代码的意图。
您甚至可以使用Comparator::comparing
方法来缩短代码:
List.of(List.of(1, 2, 5), List.of(0, 1, 2), List.of(8, 0, 0))
.stream()
.min(Comparator.comparing(Collections::max))
.get();
让我们更详细地了解这里发生的事情。
List.of(List.of(1, 2, 5), List.of(0, 1, 2), List.of(8, 0, 0))
// lets get stream of list Stream<List<Integer>>.
.stream()
// find sublist which has minimum maximum element.
.min((a, b) ->
// a & b are sublist, for example: [1,2,5], [0,1,2]
// find maximum from a [1,2,5] which is [5]
a.stream().max(Integer::compare).get()
// compare maximum from a to maximum from b
.compareTo(
// find maximum from a [0,1,2] which is [2]
b.stream().max(Integer::compare).get()
)
// get minimum out of [5,2]
).get(); // [0, 1, 2]
所以执行看起来可能与此类似:
Initial list is: [1,2,5], [0,1,2], [8, 0, 0]
find minimum list based on maximum:
min( max([1,2,5]), max([0,1,2]))
min( [5], [2])
[2] -> list [0,1,2] contains minimum maximum element so far, go the the next iteration
find minimum list based on maximum:
min( max([0,1,2]), max([8, 0, 0]) )
min( [2], [8])
[2] -> list [0,1,2] contains minimum maximum element so far,
there no other element in the stream, [0,1,2] is final result.
希望您觉得这有用。