296. 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.
解题思路:
我的想法是,首先找到所有为1的点,用一个vector存储起来
再遍历整个矩阵并计算每个点到其他房子的距离,取最小值返回。
时间复杂度为O(mnk)其中k为为1的点。
再来看看最快的解法:
参考解释:6ms C++ one pass O(mn) solution no sort, Easiest Solution O(n) + O(m) extra space
因为我们使用的是汉密尔顿距离,而汉密尔顿距离的水平距离和垂直距离是相互独立的,并不会互相影响。
代码:
O(mnk):
class Solution { public: int minTotalDistance(vector<vector<int>>& grid) { vector<pair<int,int>> peoples; int m = grid.size(), n = grid[0].size(); for(int i = 0 ; i < m; i++){ for(int j = 0; j < n; j++){ if(grid[i][j] == 1) peoples.push_back({i,j}); } } int ret = INT_MAX; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ int cur = 0; pair<int,int> pos = {i, j}; for(auto p : peoples){ cur += calDistance(p,pos); } ret = min(cur, ret); } } return ret; } int calDistance(pair<int,int> a, pair<int,int> b){ return abs(a.first - b.first) + abs(a.second - b.second); } };
最快的解法:
class Solution { public: int findDist(const vector<int>& points) { int dist = 0; int i = 0; int j = points.size() - 1; while (i < j) { dist += (points[j] - points[i]); ++i; --j; } return dist; } int minTotalDistance(vector<vector<int>>& grid) { vector<int> rows; vector<int> cols; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[0].size(); ++j) { if (grid[i][j] == 1) { rows.push_back(i); } } } for (int i = 0; i < grid[0].size(); ++i) { for (int j = 0; j < grid.size(); ++j) { if (grid[j][i] == 1) { cols.push_back(i); } } } int ans = findDist(rows) + findDist(cols); return ans; } };