LeetCode.54(59) Spiral Matrix && II
来源:互联网 发布:数控车床编程实例简单 编辑:程序博客网 时间:2024/06/13 10:12
题目54:
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]
.
class Solution { public List<Integer> spiralOrder(int[][] matrix) { //给定矩阵,螺旋输出其所有元素 //思路:顺序为:右->下->左->上,每次走完一个方向,及时更新m或者n,就判断是否满足往下一个方向的行走 List<Integer> list=new ArrayList<>(); if(matrix.length==0){ return list; } int rowBegin=0,rowEnd=matrix.length-1; int colBegin=0,colEnd=matrix[0].length-1; //保证begin小于等于end while(rowBegin<=rowEnd&&colBegin<=colEnd){ //右 for(int j=colBegin;j<=colEnd;j++){ list.add(matrix[rowBegin][j]); } //更新row rowBegin++; //下 for(int i=rowBegin;i<=rowEnd;i++){ list.add(matrix[i][colEnd]); } //更新col colEnd--; //判断是否有空间往回走 if(rowBegin<=rowEnd){ //左 for(int j=colEnd;j>=colBegin;j--){ list.add(matrix[rowEnd][j]); } } //更新 rowEnd--; //判断是否有空间往上走 if(colBegin<=colEnd){ for(int i=rowEnd;i>=rowBegin;i--){ list.add(matrix[i][colBegin]); } } //更新 colBegin++; } return list; }}
题目(59):
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
分析:
class Solution { public int[][] generateMatrix(int n) { //类似sprial matrix给定矩阵,返回数据。该题给定数据,返回矩阵。 int [][] matrix=new int[n][n]; int rowBegin=0,rowEnd=n-1; int colBegin=0,colEnd=n-1; int count=1; while(rowBegin<=rowEnd&&colBegin<=colEnd){ //右 for(int i=colBegin;i<=colEnd;i++){ matrix[rowBegin][i]=count; count++; } rowBegin++; //下 for(int i=rowBegin;i<=rowEnd;i++){ matrix[i][colEnd]=count; count++; } colEnd--; //左 if(rowBegin<=rowEnd){ for(int i=colEnd;i>=colBegin;i--){ matrix[rowEnd][i]=count; count++; } } rowEnd--; //上 if(colBegin<=colEnd){ for(int i=rowEnd;i>=rowBegin;i--){ matrix[i][colBegin]=count; count++; } } colBegin++; } return matrix; }}
阅读全文
0 0
- LeetCode(54)(59) Spiral Matrix I II
- LeetCode.54(59) Spiral Matrix && II
- LeetCode 59: Spiral Matrix II
- [leetcode 59] Spiral Matrix II
- [LeetCode 59] Spiral Matrix II
- leetcode || 59、 Spiral Matrix II
- Spiral Matrix II - LeetCode 59
- Leetcode #59 Spiral Matrix II
- leetcode 59: Spiral Matrix II
- Leetcode#59||Spiral Matrix II
- leetcode 59:Spiral Matrix II
- 【LEETCODE】59-Spiral Matrix II
- 【leetcode】【59】Spiral Matrix II
- LeetCode 59 - Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- 【LeetCode-59】Spiral Matrix II
- LeetCode 59 Spiral Matrix II
- Leetcode 59 Spiral Matrix II
- Java:类型转换案例(上)
- overflow清除浮动的真正原因
- 游戏‘微信打飞机’ 第三课
- ios_placeholder 属性与按钮倒计时功能
- 10_0类型的意义
- LeetCode.54(59) Spiral Matrix && II
- TCP三次握手与四次挥手的理解和场景举例
- 1. Two Sum
- Android VideoView播放视频只有声音没有图像黑屏
- log4j,logback,sl4j常用日志格式详解
- 哲学家就餐问题
- 实验五:用callback增强链表模块来实现命令行菜单小程序V2.8
- 数据库方言Dialect
- SpringMVC的拦截器(Interceptor)和过滤器(Filter)的区别与联系