LeetCode第 1030 题:距离顺序排列矩阵单元格(C++)

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);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值