一、题目描述
二、解题思路
2.1、整体思路
先分别按行、按列计数,然后剔除交叉点的服务器
2.2、具体分析
首先定义两个数组heng和shu,长度分别为m和n,用来统计每行和每列的服务器数量,如heng[0]表示第0行的服务器的数量,shu[0]表示第0列的服务器数量。
然后分别遍历数组heng和shu,将大于1的行和列累加到ans(初始化为0)上,由于在累加的过程中位于行列交叉点的服务器会被重复计数,因此需要遍历grid,将重复计数的服务器(横坐标x,纵坐标y,满足下列条件heng[x] > 1&&shu[y] > 1&&grid[x][y] == 1)
三、上代码(JAVA实现)
public class Media_1267 {
public int countServers(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[] heng = new int[m], shu = new int[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
heng[i] += 1;
shu[j] += 1;
}
}
}
int ans = 0;
for (int i = 0; i < m; i++) {
if (heng[i] > 1) ans += heng[i];
}
for (int j = 0; j < n; j++) {
if (shu[j] > 1) ans += shu[j];
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++){
if (heng[i] > 1 && shu[j] > 1 && grid[i][j] == 1) {
ans--;
}
}
}
return ans;
}
}
注:复制代码到力扣提交的时候注意修改类名
四、运行结果