• LeetCode 54. 螺旋矩阵


    我的LeetCode:https://leetcode-cn.com/u/ituring/

    我的LeetCode刷题源码[GitHub]:https://github.com/izhoujie/Algorithmcii

    LeetCode 54. 螺旋矩阵

    题目

    给定一个包含 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]
    

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/spiral-matrix
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解题思路

    思路1-控制横向和竖向的边界值,模拟螺旋遍历

    算法复杂度:

    • 时间复杂度: $ {color{Magenta}{Omicronleft(n ight)}} $
    • 空间复杂度: $ {color{Magenta}{Omicronleft(1 ight)}} $

    算法源码示例

    package leetcode;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @author ZhouJie
     * @date 2020年2月20日 下午2:31:13 
     * @Description: 54. 螺旋矩阵
     *
     */
    public class LeetCode_0054 {
    
    }
    
    class Solution_0054 {
    	public List<Integer> spiralOrder(int[][] matrix) {
    		List<Integer> list = new ArrayList<Integer>();
    		if (matrix == null || matrix.length == 0) {
    			return list;
    		}
    		int left, right, up, down, x, y;
    		x = y = left = up = 0;
    		right = matrix[0].length - 1;
    		down = matrix.length - 1;
    		y--;
    		while (true) {
    			if (left > right) {
    				break;
    			}
    			while (++y <= right) {
    				list.add(matrix[x][y]);
    			}
    			y--;
    			up++;
    			if (up > down) {
    				break;
    			}
    			while (++x <= down) {
    				list.add(matrix[x][y]);
    			}
    			x--;
    			right--;
    			if (left > right) {
    				break;
    			}
    			while (--y >= left) {
    				list.add(matrix[x][y]);
    			}
    			y++;
    			down--;
    			if (up > down) {
    				break;
    			}
    			while (--x >= up) {
    				list.add(matrix[x][y]);
    			}
    			x++;
    			left++;
    		}
    		return list;
    	}
    }
    
    
  • 相关阅读:
    001_jdk配置
    mysql(5.7)安装教程
    mysql(5.6)安装教程
    外网发布
    蓝桥 历届试题 分考场
    蓝桥 历届试题 合根植物
    Codeforces Round #650 (Div. 3) D : Task On The Board
    HDU 3336 Count the string
    leetcode [238. 除自身以外数组的乘积]
    leetcode [837. 新21点]
  • 原文地址:https://www.cnblogs.com/izhoujie/p/12832638.html
Copyright © 2020-2023  润新知