面试经典150题——Day35

文章目录

一、题目

54. Spiral Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]

Output: [1,2,3,6,9,8,7,4,5]

Example 2:

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]

Constraints:

m == matrix.length

n == matrix[i].length

1 <= m, n <= 10

-100 <= matrix[i][j] <= 100

二、题解

确定边界,进行模拟

cpp 复制代码
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> res;
        //左边界,右边界,上边界,下边界
        int left = 0,right = n - 1,up = 0,down = m - 1;
        while(true){
            //从左到右
            for(int j = left;j <= right;j++) res.push_back(matrix[up][j]);
            //上边界下移
            if(++up > down) break;
            //从上到下
            for(int i = up;i <= down;i++) res.push_back(matrix[i][right]);
            //右边界左移
            if(--right < left) break;
            //从右到左
            for(int j = right;j >= left;j--) res.push_back(matrix[down][j]);
            //下边界上移
            if(--down < up) break;
            //从下到上
            for(int i = down;i >= up;i--) res.push_back(matrix[i][left]);
            //左边界右移
            if(++left > right) break;
        }
        return res;
    }
};
相关推荐
杰九1 分钟前
【算法题】46. 全排列-力扣(LeetCode)
算法·leetcode·深度优先·剪枝
ephemerals__8 分钟前
【c++】动态内存管理
开发语言·c++
manba_9 分钟前
leetcode-560. 和为 K 的子数组
数据结构·算法·leetcode
liuyang-neu10 分钟前
力扣 11.盛最多水的容器
算法·leetcode·职场和发展
CVer儿17 分钟前
条件编译代码记录
开发语言·c++
忍界英雄18 分钟前
LeetCode:2398. 预算内的最多机器人数目 双指针+单调队列,时间复杂度O(n)
算法·leetcode·机器人
Kenneth風车19 分钟前
【机器学习(五)】分类和回归任务-AdaBoost算法-Sentosa_DSML社区版
人工智能·算法·低代码·机器学习·数据分析
C7211BA37 分钟前
使用knn算法对iris数据集进行分类
算法·分类·数据挖掘
Tisfy39 分钟前
LeetCode 2398.预算内的最多机器人数目:滑动窗口+单调队列——思路清晰的一篇题解
算法·leetcode·机器人·题解·滑动窗口
.普通人41 分钟前
c语言--力扣简单题目(回文链表)讲解
c语言·leetcode·链表