Skip to content

296. Best Meeting Point 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
 public:
  int minTotalDistance(vector<vector<int>>& grid) {
    const int m = grid.size();
    const int n = grid[0].size();
    vector<int> I;  // i indices s.t. grid[i][j] == 1
    vector<int> J;  // j indices s.t. grid[i][j] == 1

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (grid[i][j])
          I.push_back(i);

    for (int j = 0; j < n; ++j)
      for (int i = 0; i < m; ++i)
        if (grid[i][j])
          J.push_back(j);

    // sum(i - median(I)) + sum(j - median(J))
    return minTotalDistance(I) + minTotalDistance(J);
  }

 private:
  int minTotalDistance(const vector<int>& grid) {
    int sum = 0;
    int i = 0;
    int j = grid.size() - 1;
    while (i < j)
      sum += grid[j--] - grid[i++];
    return sum;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
  public int minTotalDistance(int[][] grid) {
    final int m = grid.length;
    final int n = grid[0].length;
    List<Integer> I = new ArrayList<>(); // i indices s.t. grid[i][j] == 1
    List<Integer> J = new ArrayList<>(); // j indices s.t. grid[i][j] == 1

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (grid[i][j] == 1)
          I.add(i);

    for (int j = 0; j < n; ++j)
      for (int i = 0; i < m; ++i)
        if (grid[i][j] == 1)
          J.add(j);

    // sum(i - median(I)) + sum(j - median(J))
    return minTotalDistance(I) + minTotalDistance(J);
  }

  private int minTotalDistance(List<Integer> grid) {
    int sum = 0;
    int i = 0;
    int j = grid.size() - 1;
    while (i < j)
      sum += grid.get(j--) - grid.get(i++);
    return sum;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def minTotalDistance(self, grid: list[list[int]]) -> int:
    m = len(grid)
    n = len(grid[0])
    # i indices s.t. grid[i][j] == 1
    I = [i for i in range(m) for j in range(n) if grid[i][j]]
    # j indices s.t. grid[i][j] == 1
    J = [j for j in range(n) for i in range(m) if grid[i][j]]

    def minTotalDistance(grid: list[int]) -> int:
      summ = 0
      i = 0
      j = len(grid) - 1
      while i < j:
        summ += grid[j] - grid[i]
        i += 1
        j -= 1
      return summ

    # sum(i - median(I)) + sum(j - median(J))
    return minTotalDistance(I) + minTotalDistance(J)