每天一道算法题系列:
来源:力扣(LeetCode)
本题链接:https://leetcode-cn.com/problems/spiral-matrix/
来源是力扣,大家喜欢可以去力扣中文网做相应的其他的题,某浏览器直接搜力扣即可。
本题难度是中等
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
这道题我的做法就是究极旋转大法,说白了就是一圈一圈更着走,代码其实很简单,看看就懂了,主要判断的就是left<right,top<bottom
public List<Integer> spiralOrder(int[][] matrix) {
LinkedList<Integer> result = new LinkedList<>();
if(matrix==null||matrix.length==0) return result;
int left = 0;
int right = matrix[0].length - 1;
int top = 0;
int bottom = matrix.length - 1;
//得到所有的数,然后对他进行循环遍历,遍历一次就--
int num = matrix.length * matrix[0].length;
//在后面必须要判断num是否大于0,大于0就继续运行,小于0就return
while(num > 0){
for(int i= left ;i <= right && num > 0;i++){
result.add(matrix[top][i]);
num --;
}
top ++;
for(int i = top ;i <= bottom && num > 0 ; i++ ){
result.add(matrix[i][right]);
num --;
}
right -- ;
for(int i = right;i >= left && num > 0;i--){
result.add(matrix[bottom][i]);
num --;
}
bottom--;
for(int i = bottom;i >= top && num > 0;i--){
result.add(matrix[i][left]);
num --;
}
left++;
}
return result;
}
上一篇文章:每天一道算法题系列三十四之最大子序和
如果本篇内容有问题,请第一时间联系我,我会第一时间修改。
谢谢大家。