当前位置:网站首页>LeetCode腾讯精选练习50题-054.螺旋矩阵
LeetCode腾讯精选练习50题-054.螺旋矩阵
2022-07-16 09:20:00 【whtli】
题目描述
- 给定一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
example
input : matrix = [[1,2,3],[4,5,6],[7,8,9]]
output : [1,2,3,6,9,8,7,4,5]
input : matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
output : [1,2,3,4,8,12,11,10,9,5,6,7]
解题思路 按层模拟
- 按照题目要求的转圈遍历顺序,使用上下左右四个界限坐标来标记每圈的位置,模拟整个向内环绕的元素获取过程。
- 时间复杂度:O(m×n)
- 空间复杂度:O(1)
代码(Java)
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<>();
int length = matrix.length;
int width = matrix[0].length;
int left = 0, right = width - 1, top = 0, bottom = length - 1;
while (left <= right && top <= bottom) {
for (int i = left; i <= right; i++) {
list.add(matrix[top][i]);
}
for (int j = top + 1; j <= bottom; j++) {
list.add(matrix[j][right]);
}
if (left < right && top < bottom) {
for (int p = right - 1; p >= left; p--) {
list.add(matrix[bottom][p]);
}
for (int q = bottom - 1; q > top; q--) {
list.add(matrix[q][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return list;
}
}
边栏推荐
- CF609A USB Flash Drives
- uniapp扫码原生插件(Google MLKit、zxing;支持同时扫多个码)
- HCIP - GRE/MGRE、OSPF
- JS variable points you don't know
- PG operation and maintenance -- error log and slow log
- Joint autoregressive and hierarchical priorities for learned image compression
- Zhongguancun e valley · Su Gaoxin undertakes 2022 Suzhou China Japan South Korea high-level talent project roadshow competition
- Interviewer: what are the methods of redis performance optimization?
- 关于唐医生的一切:真实的中国人工心脏是什么样?
- ##负载均衡LVS集群详解##
猜你喜欢

9. 说说hashCode() 和 equals() 之间的关系?

ValueError: The number of FixedLocator locations (7), usually from a call to set_ ticks, does not mat

CF514B Han Solo and Lazer Gun

Comprehensively analyze the liquidity problems and solutions of NFT

【无标题】伪类选择器和盒模型

OSPF的5个数据包、LSA信息
聊一聊Promise

1388. 3n 块披萨 动态规划

JS变量你不知道的点

高等数学---第八章隐函数偏导数与全微分
随机推荐
CF514B Han Solo and Lazer Gun
1388. 3n 块披萨 动态规划
容器健康检查解析
Elk cluster deployment (IV) deployment logstash
query string、formData和request payload的区别
实现团队工作效率与质量共赢,这款办公协同工具真够用!
A collection of dichotomous (dichotomous answers) questions
[binary tree] all elements in two binary search trees
Talk about promise
自定义类型下(枚举、联合)C语言
流动性视角中 CeFi 的功与过
Logback different packages (business logs) are output to different log files
使用IDEA搭建WebService服务
High-Resolution Network (篇二):MMpose代码讲解之Backbone及关键点Detector部分
【无标题】伪类选择器和盒模型
sqoop 从mysql 导入json格式中文乱码
How to extract value from the working capital pool by using impermanent losses
NFT players' consensus segmentation: money, community and culture
重邮SYDTEK实习(一): 4k和BLE profile烧录
465 sword finger offer (53-i, 53-ii, 04, 50)