LeetCode54 Spiral Matrix
2024-09-06 14:47:12
题目:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5]
. (Medium)
分析:
题目没有什么复杂的算法要应用,就是一行一列输出,处理好细节即可。
比较清晰的写法是搞一个rowBegin, rowEnd, colBegin, colEnd, 并在处理完一行/一列后更新值,并判断是否仍然满足 rowBegin <= rowEnd && colBegin <= colEnd
代码:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
if (matrix.size() == ) {
return result;
}
int m = matrix.size(), n = matrix[].size();
int rowBegin = , rowEnd = m - , colBegin = , colEnd = n - ;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
for (int i = colBegin; i <= colEnd; ++i ) {
result.push_back(matrix[rowBegin][i]);
}
rowBegin++;
if (rowBegin > rowEnd) {
break;
}
for (int i = rowBegin; i <= rowEnd; ++i) {
result.push_back(matrix[i][colEnd]);
}
colEnd--;
if (colBegin > colEnd) {
break;
}
for (int i = colEnd; i >= colBegin; --i) {
result.push_back(matrix[rowEnd][i]);
}
rowEnd--;
if (rowBegin > rowEnd) {
break;
}
for (int i = rowEnd; i>= rowBegin; --i) {
result.push_back(matrix[i][colBegin]);
}
colBegin++;
}
return result;
}
};
最新文章
- java web学习总结(十二) -------------------Session
- php curl用法
- ionic不同view跳转到同一个
- BZOJ3898 : 打的士
- cocos2dx 3.x(屏幕截图的两种方法)
- 关于iPhone多点触控
- Http抓包工具Charlse使用教程
- Swift中的延迟加载(懒加载)
- Ubuntu apache 禁止目录浏览
- socket编程——一个简单的例子
- hibernate---一对一单向主键关联(不重要)
- Android自定义控件之TextView
- 【转】IO流程
- three.js 相机
- javascript获取网页地址栏的id
- 03 Button 按钮
- 服务器端配置nodejs环境(使用pm2进程管理运行)
- Linux系统KVM虚拟化技术
- HotSpot虚拟机
- python3编译安装no module named _ssl
热门文章
- DynamicDataDisplay 双击获取坐标
- JavaScript如何实现字符串拼接操作
- [jnhs]hibernate只能创建一张/表不创建表com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table &#39;kaihu.t_client_info&#39; doesn&#39;t exist和org.hibernate.exception.SQLGrammarException: could not execute statement
- TomCat 启动默认加载项目
- Ubuntu18.04 修改IP地址、查看网关、防火墙
- 验证码倒计时js
- RSA 2019安全大会:企业资产管理成行业新风向标,云上安全占优势
- 阿里云杨敬宇:5G时代,边缘计算将发挥更大价值
- 【python之路15】深浅拷贝及函数
- 层次分析法MATLAB