1030. 距离顺序排列矩阵单元格 - 力扣(LeetCode)
其实就是定义一个排序规则的问题
使用优先级队列
class Solution {
public:
vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {
vector<vector<int>> res;
//https://blog.csdn.net/qq_32523711/article/details/108226095
auto cmp = [&r0, &c0](const vector<int> &a, const vector<int> &b){return abs(a[0]-r0) + abs(a[1]-c0) > abs(b[0]-r0) + abs(b[1]-c0);};
priority_queue<vector<int>, vector<vector<int>>, decltype(cmp)> q(cmp);
for(int i = 0; i < R; ++i){
for(int j = 0; j < C; ++j) q.push({i, j});
}
while(!q.empty()){
res.push_back(q.top());
q.pop();
}
return res;
}
};
排序
class Solution {
public:
vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {
vector<vector<int>> res;
for(int i = 0; i < R; ++i){
for(int j = 0; j < C; ++j) res.push_back({i, j});
}
sort(res.begin(), res.end(), [&r0, &c0](const vector<int> &a, const vector<int> &b){
return abs(a[0]-r0) + abs(a[1]-c0) < abs(b[0]-r0) + abs(b[1]-c0);
});
return res;
}
};
复杂度比较高
桶排序
由于数据量并不大,分桶比较容易
class Solution {
public:
vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {
int maxDis = max(r0, R-1-r0) + max(c0, C-1-c0);
vector<vector<int>> bucket[maxDis+1];
for(int i = 0; i < R; ++i){
for(int j = 0; j < C; ++j){
int dis = abs(i-r0) + abs(j-c0);
bucket[dis].push_back({i, j});
}
}
vector<vector<int>> res;
for(int i = 0; i <= maxDis; ++i){
for(auto &v : bucket[i]) res.push_back(v);
}
return std::move(res);
}
};