一行中特定列的最大值



我有以下二维数组:

1 | 5 | 6 | 16| 8 | 9 | 
9 | 1 | 3 | 4 | 7 | 6 | 
1 | 2 | 4 | 7 | 3 | 8 |
int[][] arr = {{1 ,5 ,6 ,16,8 ,9 }, {9 ,1 ,3 ,4 ,7 ,6 }, {1 ,2 ,4 ,7 ,3 ,8 }};

我需要找到特定行和列的最大值,例如第一行,第二列和第五列的最大值是8。

使用流API是很方便的:

public static int findMax(int from, int to, int row, int[][] arr) {
// validate input parameters
assert 0 <= row && row < arr.length;
assert 0 <= from && from <= to && to < arr[row].length;
return Arrays.stream(arr[row])     // IntStream of numbers in the given row
.skip(from)           // start `from` column
.limit(to - from + 1) // check until `to` column
.max()                // pick max value
.orElse(Integer.MIN_VALUE); // if max not found (empty array)
}

测试:

int[][] arr = {
{1, 5, 6, 7, 8, 9 },
{9, 1, 3, 4, 7, 6},
{1, 2, 4, 7, 3, 8}
};
System.out.println(findMax(1, 2, 0, arr));

输出:

6

同样可以使用普通循环实现:

public static int findMax(int from, int to, int row, int[][] arr) {
assert 0 <= row && row < arr.length;
assert 0 <= from && from <= to && to < arr[row].length;
int max = Integer.MIN_VALUE;
for (int i = from; i <= to; i++) {
max = Math.max(max, arr[row][i]);
}
return max;
}

注意:在这两个示例中,以0为基础的数组索引用于行和列:1表示第二列,2表示第三列,0表示第一行。


更新
由于可能需要在一组列(不包括两列之间)中查找最大值,因此可以实现为:

public static int findMaxInColumns(int[][] arr, int row, int ... cols) {
assert 0 <= row && row < arr.length;
return Arrays.stream(cols)
// optional filter to prevent ArrayOutOfBoundsException
.filter(col -> col >= 0 && col < arr[row].length)
.map(col -> arr[row][col])
.max()
.orElse(Integer.MIN_VALUE );
}

相同arr的测试:

System.out.println("max in cols 1, 3, 4: " + findMaxInColumns(arr, 0, 1, 3, 4));

输出:

max in cols 1, 3, 4: 8

如果你从1开始索引,那么你可以这样做:

int[][] arr = {{1, 5, 6, 7, 8, 9}, {9, 1, 3, 4, 7, 6}, {1, 2, 4, 7, 3, 8}};
int rowNum = 1;
int firstColNum = 2;
int lastColNum = 3;
int maxVal = Arrays.stream(arr[rowNum-1])
.limit(lastColNum)
.skip(firstColNum)
.max().getAsInt();
System.out.println(maxVal);

你可以把你的行和冷值放在数组或列表中:

int[][] arr = {{1, 5, 6, 16, 8, 9}, {9, 1, 3, 4, 7, 6}, {1, 2, 4, 7, 3, 8}};
Integer maxVal = null;
int[] rowNums = {1};
int[] colNums = {5,1};
List<Integer> resList = new ArrayList();
for (int rowIndx : rowNums) {
for (int colIndx : colNums) {
int currVal = arr[rowIndx - 1][colIndx - 1];
if (maxVal==null) maxVal=currVal;
else if (maxVal < currVal) maxVal = currVal;
}
}
System.out.println(maxVal);

或者你可以用更复杂的方式使用流API:

int[][] arr = {{1 ,5 ,6 ,16,8 ,9 }, {9 ,1 ,3 ,4 ,7 ,6 }, {1 ,2 ,4 ,7 ,3 ,8 }};
//set list of rows 
List<Integer> rowNums = Arrays.asList(1);
//set list of columns 
List<Integer> colNums = Arrays.asList(1,5);
int maxVal = rowNums.stream().map(i -> arr[i-1])
.flatMapToInt(innerArr -> colNums.stream()
.mapToInt(i -> innerArr[i-1]))
.max().getAsInt();
System.out.println(maxVal);

最新更新