在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column. Return the number of servers that communicate with any other server. Example 1: Input: grid = [[1,0],[0,1]] Input: grid = [[1,0],[1,1]] Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]] Constraints: m == grid.length 这里有一幅服务器分布图,服务器的位置标识在 m * n 的整数矩阵网格 grid 中,1 表示单元格上有服务器,0 表示没有。 如果两台服务器位于同一行或者同一列,我们就认为它们之间可以进行通信。 请你统计并返回能够与至少一台其他服务器进行通信的服务器的数量。 示例 1: 输入:grid = [[1,0],[0,1]] 输入:grid = [[1,0],[1,1]] 输入:grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]] 提示: m == grid.length Runtime: 460 ms
Memory Usage: 21 MB
1 class Solution { 2 func countServers(_ grid: [[Int]]) -> Int { 3 if grid.count == 0 || grid[0].count == 0 4 { 5 return 0 6 } 7 let numRows:Int = grid.count 8 let numCols:Int = grid[0].count 9 var rowCount:[Int] = [Int](repeating: 0, count: numRows) 10 var colCount:[Int] = [Int](repeating: 0, count: numCols) 11 var totalServers:Int = 0 12 for row in 0..<numRows 13 { 14 for col in 0..<numCols 15 { 16 if grid[row][col] == 1 17 { 18 rowCount[row] += 1 19 colCount[col] += 1 20 totalServers += 1 21 } 22 } 23 } 24 for row in 0..<numRows 25 { 26 for col in 0..<numCols 27 { 28 if grid[row][col] == 1 29 { 30 if rowCount[row] == 1 && colCount[col] == 1 31 { 32 totalServers -= 1 33 } 34 } 35 } 36 } 37 return totalServers 38 } 39 }
|
请发表评论