在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = For example, given three people living at 1 - 0 - 0 - 0 - 1 | | | | | 0 - 0 - 0 - 0 - 0 | | | | | 0 - 0 - 1 - 0 - 0 The point Hint:
两个或两个以上的人组成的一个小组,他们想要满足并尽量减少总的旅行距离。您将得到一个值为0或1的二维网格,其中每个1标记组中某个人的家。使用曼哈顿距离计算距离,其中距离(p1, p2) = 例如,假设有三个人生活在 1 - 0 - 0 - 0 - 1 | | | | | 0 - 0 - 0 - 0 - 0 | | | | | 0 - 0 - 1 - 0 - 0 点(0,2)是一个理想的汇合点,因为2+2+2=6的总行驶距离是最小的。所以返回6。 提示: 首先试着用一维来解决它。这个解决方案如何适用于二维情况? Solution: 1 class Solution { 2 func minTotalDistance(_ grid:inout [[Int]]) -> Int { 3 var rows:[Int] = [Int]() 4 var cols:[Int] = [Int]() 5 for i in 0..<grid.count 6 { 7 for j in 0..<grid[i].count 8 { 9 if grid[i][j] == 1 10 { 11 rows.append(i) 12 cols.append(j) 13 } 14 } 15 } 16 cols.sort() 17 var res:Int = 0 18 var i:Int = 0 19 var j:Int = rows.count - 1 20 while(i < j) 21 { 22 res += (rows[j] - rows[i] + cols[j] - cols[i] ) 23 j -= 1 24 i += 1 25 } 26 return res 27 } 28 } 点击:Playground测试 1 var sol = Solution() 2 var grid:[[Int]] = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]] 3 print(sol.minTotalDistance(&grid)) 4 //Print 6
|
请发表评论