LeetCode 296. Best Meeting Point Minimum Moves to Equal Array Elements II

原题链接在这里:https://leetcode.com/problems/best-meeting-point/

题目:

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) = |p2.x - p1.x| + |p2.y - p1.y|.

Example:

Input: 

1 - 0 - 0 - 0 - 1
|   |   |   |   |
0 - 0 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 1 - 0 - 0

Output: 6 

Explanation: Given three people 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.

题解:

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 }

类似Minimum Moves to Equal Array Elements II.

猜你喜欢

转载自www.cnblogs.com/Dylan-Java-NYC/p/12154513.html