Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
best-meeting-point.cpp 910 Bytes
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-01-04 22:40 +08:00 . Update best-meeting-point.cpp
// Time: O(m * n)
// Space: O(m + n)
class Solution {
public:
int minTotalDistance(vector<vector<int>>& grid) {
vector<int> x, y;
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[0].size(); ++j) {
if (grid[i][j]) {
x.emplace_back(i);
y.emplace_back(j);
}
}
}
nth_element(x.begin(), x.begin() + x.size() / 2, x.end());
nth_element(y.begin(), y.begin() + y.size() / 2, y.end());
const int mid_x = x[x.size() / 2];
const int mid_y = y[y.size() / 2];
int sum = 0;
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[0].size(); ++j) {
if (grid[i][j]) {
sum += abs(mid_x - i) + abs(mid_y - j);
}
}
}
return sum;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助