LeetCode 296. Best Meeting Point
原题链接在这里:https://leetcode.com/problems/best-meeting-point/
题目:
Given an m x n
binary grid grid
where each 1
marks the home of one friend, return the minimal total travel distance.
The total travel distance is the sum of the distances between the houses of the friends and the meeting point.
The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|
.
Example 1:
Input: grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]] Output: 6 Explanation: Given three friends living at (0,0), (0,4), and (2,2). The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal. So return 6.
Example 2:
Input: grid = [[1,1]] Output: 1
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
grid[i][j]
is either0
or1
.- There will be at least two friends in the
grid
.
题解:
When trying to minimize the manhattan distance, it is trying to minimize the absolute deviations of x and y.
And median minimize the absolute deviations.
We get all x and y when there is a building.
And calculate absolute deviations.
Time Complexity: O(m * n). m = grid.length. n = grid[0].length.
Space: O(m + n).
AC Java:
1 class Solution { 2 public int minTotalDistance(int[][] grid) { 3 if(grid == null || grid.length == 0 || grid[0].length == 0){ 4 return 0; 5 } 6 7 int m = grid.length; 8 int n = grid[0].length; 9 10 List<Integer> iIndexList = new ArrayList<>(); 11 for(int i = 0; i < m ; i++){ 12 for(int j = 0; j < n; j++){ 13 if(grid[i][j] == 1){ 14 iIndexList.add(i); 15 } 16 } 17 } 18 19 List<Integer> jIndexList = new ArrayList<>(); 20 for(int j = 0; j < n; j++){ 21 for(int i = 0; i < m; i++){ 22 if(grid[i][j] == 1){ 23 jIndexList.add(j); 24 } 25 } 26 } 27 28 int iDist = dist(iIndexList); 29 int jDist = dist(jIndexList); 30 return iDist + jDist; 31 } 32 33 private int dist(List<Integer> list){ 34 int l = 0; 35 int r = list.size() - 1; 36 int res = 0; 37 38 while(l < r){ 39 res += list.get(r--) - list.get(l++); 40 } 41 42 return res; 43 } 44 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步