系列文章目录
前言
一、剑指 Offer 29. 顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100
作者:Krahets
链接:https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5vfh9g/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
二、使用步骤
1.引入库
代码如下:
方法一:普通解法
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
if (matrix.empty()) return {};
int l = 0, r = matrix[0].size() - 1, t = 0, b = matrix.size() - 1;
vector<int> res;
while(true)
{
for (int i = l; i <= r; i++) res.push_back(matrix[t][i]); // left to right
if (++t > b) break;
for (int i = t; i <= b; i++) res.push_back(matrix[i][r]); // top to bottom
if (l > --r) break;
for (int i = r; i >= l; i--) res.push_back(matrix[b][i]); // right to left
if (t > --b) break;
for (int i = b; i >= t; i--) res.push_back(matrix[i][l]); // bottom to top
if (++l > r) break;
}
return res;
}
};
消耗
执行用时:
12 ms
, 在所有 C++ 提交中击败了
73.75%
的用户
内存消耗:
9.8 MB
, 在所有 C++ 提交中击败了
43.16%
的用户
方法二:神仙解法
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
while matrix:
res += matrix.pop(0)
matrix = list(zip(*matrix))[::-1]
return res
https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/solution/mian-shi-ti-29-shun-shi-zhen-da-yin-ju-zhen-she-di/
见第一条评论
顺时针旋转90度:matrix = map(list, zip(*(matrix[::-1])))
消耗
执行用时:
68 ms
, 在所有 Python3 提交中击败了
14.41%
的用户
内存消耗:
15.7 MB
, 在所有 Python3 提交中击败了
10.14%
的用户
总结
以上就是今天要讲的内容