当前位置:   article > 正文

剑指Offer——顺序打印数组_依次打印数组元素

依次打印数组元素

  本博客为刷题笔记,方便日后复习。
  刷题平台:Leedcode

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例1:

	输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
	输出:[1,2,3,6,9,8,7,4,5]
  • 1
  • 2

示例2:

	输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
	输出:[1,2,3,4,8,12,11,10,9,5,6,7]
  • 1
  • 2

限制:

	0 <= matrix.length <= 100
	0 <= matrix[i].length <= 100
  • 1
  • 2

题目分析

  我们可以将矩阵看出若干个层,首先打印最外层的元素,然后打印次外层的元素。直到答打印最内初层的元素。
  我们通过一个具体的例子来看看。如图1所示。我们定义一个vector存储结果,我们假设当前层的左上角的位于(top,left),右下角位于(bottom,right),按照 如下方法遍历。

  1. 从左到右遍历上侧元素,依次为 (top, left) 到(top,right)。
  2. 从上到下遍历右侧元素,依次为(top+1,right) 到 (bottom,right)。
  3. 如果 left<right 且top<bottom,则从右到左遍历下侧元素,依次为(bottom,right−1) 到 (bottom,left+1),以及从下到上遍历左侧元素,依次为 (bottom,left) 到(top+1,left)。

遍历完当前层的元素之后,将 left 和top 分别增加 1,将 right 和 bottom 分别减少 1,进入下一层继续遍历,直到遍历完所有元素为止。

图1. 二维数组

代码实现

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
		// 二维数组为空,返回空数组
        if (matrix.size() == 0 || matrix[0].size() == 0) {
            return {};
        }
        int rows = matrix.size(), columns = matrix[0].size();
		//定义vector存储结果
        vector<int> order;
		//定义left,right,top,bottom确定位置
        int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
		//遍历打印
        while (left <= right && top <= bottom) {
			//从左到右
            for (int column = left; column <= right; column++) {
                order.push_back(matrix[top][column]);
            }
			//从上到下
            for (int row = top + 1; row <= bottom; row++) {
                order.push_back(matrix[row][right]);
            }

            if (left < right && top < bottom) {
				//从右到左
                for (int column = right - 1; column > left; column--) {
                    order.push_back(matrix[bottom][column]);
                }
				//从下到上
                for (int row = bottom; row > top; row--) {
                    order.push_back(matrix[row][left]);
                }
            }
            
            left++;
            right--;
            top++;
            bottom--;
        }
        return order;
    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/1005094
推荐阅读
相关标签
  

闽ICP备14008679号