Sort the Matrix Diagonally(C++将矩阵按对角线排序)

459 篇文章 1 订阅

解题思路:

(1)先找一个顺序,从下往上,从左到右

(2)先排序再赋值

class Solution {
public:
    vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {
        int row = mat.size()-1;
        int col = mat[0].size()-1;
        
        //排序
        vector<vector<int>> vec;
        for(int i=row;i>=0;i--) {
            vector<int> v;
            int j=0,temp=i;
            while(temp<=row && j<=col) {
                v.push_back(mat[temp][j]);
                temp++;
                j++;
            }
            sort(v.begin(),v.end());
            vec.push_back(v);
        }
        
        for(int i=1;i<=col;i++) {
            vector<int> v;
            int j=0,temp=i;
            while(temp<=col && j<=row) {
                v.push_back(mat[j][temp]);
                temp++;
                j++;
            }
            sort(v.begin(),v.end());
            vec.push_back(v);
        }
        
        //赋值
        for(int i=row;i>=0;i--) {
            int j=0,temp=i,count=0;
            while(temp<=row && j<=col) {
                mat[temp][j] = vec[row-i][count];
                temp++;
                j++;
                count++;
            }
        }
        
        for(int i=1;i<=col;i++) {
            int j=0,temp=i,count=0;
            while(temp<=col && j<=row) {
                mat[j][temp] = vec[row+i][count];
                temp++;
                j++;
                count++;
            }
        }
        
        return mat;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值