赞
踩
原题目:https://leetcode-cn.com/problems/sort-the-matrix-diagonally/
思路:
用临时数组存储每一个对角线的元素,排序后,赋值给新的矩阵对角线即可
代码:
- class Solution {
- public:
- vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {
- if(mat.size()==0 || mat[0].size()==0) return mat;
- int n = mat.size(),m = mat[0].size();
- vector<vector<int>> ans(n,vector<int>(m));
-
- for(int i=m-1;i>=0;--i){
- int row=0,col=i,index=-1;
- vector<int> tmp;
- while(row<n&&col<m){
- tmp.push_back(mat[row][col]);
- ++row;++col;
- }
- sort(tmp.begin(),tmp.end());
- row=0,col = i;
- while(row<n&&col<m){
- ans[row][col] = tmp[++index];
- ++row;++col;
- }
- }
- for(int i=1;i<n;++i){
- int row=i,col=0,index=-1;
- vector<int> tmp;
- while(row<n&&col<m){
- tmp.push_back(mat[row][col]);
- ++row;++col;
- }
- sort(tmp.begin(),tmp.end());
- row=i,col = 0;
- while(row<n&&col<m){
- ans[row][col] = tmp[++index];
- ++row;++col;
- }
- }
- return ans;
- }
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。