【leetcode_medium】54. Spiral Matrix
leetcode_medium_array
problem
solution #1: traverse from left to right, and then from down to up;
code
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> res; if(matrix.empty()) return res; int m = matrix.size(); int n = matrix[0].size(); int up = 0, down = m-1, left = 0, right = n-1; while(left<=right && up<=down ) // && res.size()<m*n { // why do check res.size in every for loop? for(int i=left; i<=right&& res.size()<m*n; i++) { res.push_back(matrix[up][i]); } up++; for(int i=up; i<=down&& res.size()<m*n; i++) { res.push_back(matrix[i][right]); } right--; for(int i=right; i>=left&& res.size()<m*n; i--) { res.push_back(matrix[down][i]); } down--; for(int i=down; i>=up&& res.size()<m*n; i--) { res.push_back(matrix[i][left]); } left++; } return res; } };
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> res; if(matrix.empty()) return res; int m = matrix.size(); int n = matrix[0].size(); int up = 0, down = m-1, left = 0, right = n-1; while(left<=right && up<=down ) // && res.size()<m*n { // why do check res.size in every for loop? for(int i=left; i<=right&& res.size()<m*n; i++) { res.push_back(matrix[up][i]); } up++; for(int i=up; i<=down&& res.size()<m*n; i++) { res.push_back(matrix[i][right]); } right--; for(int i=right; i>=left&& res.size()<m*n; i--) { res.push_back(matrix[down][i]); } down--; for(int i=down; i>=up&& res.size()<m*n; i--) { res.push_back(matrix[i][left]); } left++; } return res; } };
solution #2:
code
solution #3:使用switch语句;
code:
参考
1. leetcode_54. Spiral Matrix;
完
各美其美,美美与共,不和他人作比较,不对他人有期待,不批判他人,不钻牛角尖。
心正意诚,做自己该做的事情,做自己喜欢做的事情,安静做一枚有思想的技术媛。
版权声明,转载请注明出处:https://www.cnblogs.com/happyamyhope/
心正意诚,做自己该做的事情,做自己喜欢做的事情,安静做一枚有思想的技术媛。
版权声明,转载请注明出处:https://www.cnblogs.com/happyamyhope/