# 你如何找到一个整数二维数组中拥有最多0值的行？

go评论18阅读模式

How can i find the row which has the most 0 values in an int 2D array?

# 问题

``````int[][] arr = new int[4][5];
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[0][3] = 4;

arr[1][0] = 29;
arr[1][1] = 28;
arr[1][2] = 27;

arr[2][0] = 3;
arr[2][1] = 33;

arr[3][0] = 41;
arr[3][1] = 42;
arr[3][2] = 43;
arr[3][3] = 43;
``````

How can i find the row which has the most 0 values in an int 2D array?

Example:

``````int[][] arr = new int[4][5];
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[0][3] = 4;

arr[1][0] = 29;
arr[1][1] = 28;
arr[1][2] = 27;

arr[2][0] = 3;
arr[2][1] = 33;

arr[3][0] = 41;
arr[3][1] = 42;
arr[3][2] = 43;
arr[3][3] = 43;
``````

The answer is should be Row index 2

# 答案1

``````int[][] arr = new int[4][5];
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[0][3] = 4;

arr[1][0] = 29;
arr[1][1] = 28;
arr[1][2] = 27;

arr[2][0] = 3;
arr[2][1] = 33;

arr[3][0] = 41;
arr[3][1] = 42;
arr[3][2] = 43;
arr[3][3] = 43;

IntStream.range(0, arr.length).boxed()
.map(row -> Map.entry(row, Arrays.stream(arr[row]).filter(i -> i != 0).count()))
.min(Comparator.comparing(Entry::getValue))
.map(Entry::getKey)
.ifPresent(row -> System.out.println("行: " + row));
``````

``````行: 2
``````

``````int row = -1;
int maxZeros = 0;

for (int i = 0; i < arr.length; i++) {
int zeros = 0;
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 0) {
zeros++;
}
}
if (zeros > maxZeros) {
maxZeros = zeros;
row = i;
}
}

if (row > -1) {
System.out.println("行: " + row);
}
``````

``````行: 2
``````

There are several ways to achieve your goal. I would use `stream`s for that job:

``````    int[][] arr = new int[4][5];
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[0][3] = 4;

arr[1][0] = 29;
arr[1][1] = 28;
arr[1][2] = 27;

arr[2][0] = 3;
arr[2][1] = 33;

arr[3][0] = 41;
arr[3][1] = 42;
arr[3][2] = 43;
arr[3][3] = 43;

IntStream.range(0, arr.length).boxed()
.map(row -&gt; Map.entry(row, Arrays.stream(arr[row]).filter(i -&gt; i != 0).count()))
.min(Comparator.comparing(Entry::getValue))
.map(Entry::getKey)
.ifPresent(row -&gt; System.out.println(&quot;Row: &quot; + row));
``````

Output

``````Row: 2
``````

Update

If you want to use a `for loop` you can do:

``````    int row = -1;
int maxZeros = 0;

for (int i = 0; i &lt; arr.length; i++) {
int zeros = 0;
for (int j = 0; j &lt; arr[i].length; j++) {
if (arr[i][j] == 0) {
zeros++;
}
}
if (zeros &gt; maxZeros) {
maxZeros = zeros;
row = i;
}
}

if (row &gt; -1) {
System.out.println(&quot;Row: &quot; + row);
}
``````

Output

``````Row: 2
``````

• 本文由 发表于 2020年7月23日 07:32:41
• 转载请务必保留本文链接：https://go.coder-hub.com/63044621.html
• java

go 12

go 16

go 21

go 16