LeetCode 1267: Count Servers that Communicate
Problem Description
Explanation:
- We can solve this problem by counting the number of servers in each row and each column.
- For each server, if there is more than one server in its row or column, we increment the total count.
- Finally, we return the total count of servers that can communicate with at least one other server.
Time Complexity:
The time complexity of this solution is O(m * n), where m is the number of rows and n is the number of columns in the grid.
Space Complexity:
The space complexity of this solution is O(m + n), where m is the number of rows and n is the number of columns in the grid.
:
Solutions
class Solution {
public int countServers(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[] rows = new int[m];
int[] cols = new int[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
rows[i]++;
cols[j]++;
}
}
}
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1 && (rows[i] > 1 || cols[j] > 1)) {
count++;
}
}
}
return count;
}
}
Loading editor...