当前位置: 首页 > news >正文

算法leetcode|54. 螺旋矩阵(rust重拳出击)


文章目录

  • 54. 螺旋矩阵:
    • 样例 1:
    • 样例 2:
    • 提示:
  • 分析:
  • 题解:
    • rust:
    • go:
    • c++:
    • python:
    • java:
      • 每次循环移动一步:
      • 每次循环完成一个顺时针:


54. 螺旋矩阵:

给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

样例 1:

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

样例 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]

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

分析:

  • 面对这道算法题目,二当家的陷入了沉思。
  • 可以每次循环移动一步,判断移到边界就变换方向。
  • 也可以每次循环都换完4次方向,也就是完成一次顺时针,然后缩圈。

题解:

rust:

impl Solution {pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {let mut ans = Vec::new();let (rows, columns) = (matrix.len(), matrix[0].len());let (mut left, mut right, mut top, mut bottom) = (0, columns - 1, 0, rows - 1);while left <= right && top <= bottom {(left..right + 1).for_each(|column| {ans.push(matrix[top][column]);});(top + 1..bottom + 1).for_each(|row| {ans.push(matrix[row][right]);});if left < right && top < bottom {(left..right).rev().for_each(|column| {ans.push(matrix[bottom][column]);});(top + 1..bottom).rev().for_each(|row| {ans.push(matrix[row][left]);});}if right == 0 || bottom == 0 {break;}left += 1;right -= 1;top += 1;bottom -= 1;}return ans;}
}

go:

func spiralOrder(matrix [][]int) []int {rows, columns := len(matrix), len(matrix[0])left, right, top, bottom := 0, columns-1, 0, rows-1ans := make([]int, rows*columns)index := 0for left <= right && top <= bottom {for column := left; column <= right; column++ {ans[index] = matrix[top][column]index++}for row := top + 1; row <= bottom; row++ {ans[index] = matrix[row][right]index++}if left < right && top < bottom {for column := right - 1; column >= left; column-- {ans[index] = matrix[bottom][column]index++}for row := bottom - 1; row > top; row-- {ans[index] = matrix[row][left]index++}}left++right--top++bottom--}return ans
}

c++:

class Solution {
public:vector<int> spiralOrder(vector<vector<int>>& matrix) {vector<int> ans;int rows = matrix.size(), columns = matrix[0].size();int left = 0, right = columns - 1, top = 0, bottom = rows - 1;while (left <= right && top <= bottom) {for (int column = left; column <= right; ++column) {ans.emplace_back(matrix[top][column]);}for (int row = top + 1; row <= bottom; ++row) {ans.emplace_back(matrix[row][right]);}if (left < right && top < bottom) {for (int column = right - 1; column >= left; --column) {ans.emplace_back(matrix[bottom][column]);}for (int row = bottom - 1; row > top; --row) {ans.emplace_back(matrix[row][left]);}}++left;--right;++top;--bottom;}return ans;}
};

python:

class Solution:def spiralOrder(self, matrix: List[List[int]]) -> List[int]:ans = list()rows, columns = len(matrix), len(matrix[0])left, right, top, bottom = 0, columns - 1, 0, rows - 1while left <= right and top <= bottom:for column in range(left, right + 1):ans.append(matrix[top][column])for row in range(top + 1, bottom + 1):ans.append(matrix[row][right])if left < right and top < bottom:for column in range(right - 1, left - 1, -1):ans.append(matrix[bottom][column])for row in range(bottom - 1, top, -1):ans.append(matrix[row][left])left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1return ans

java:

每次循环移动一步:

class Solution {public List<Integer> spiralOrder(int[][] matrix) {List<Integer> ans = new ArrayList<Integer>();final int     rows             = matrix.length, columns = matrix[0].length;int           left             = 0, right = columns - 1, top = 0, bottom = rows - 1;final int     total            = rows * columns;int           row              = 0, column = 0;final int[][] moveDirections   = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};final int[][] borderDirections = {{1, 0, 0, 0}, {0, 0, 1, 0}, {0, -1, 0, 0}, {0, 0, 0, -1}};int           directionIndex   = 0;for (int i = 0; i < total; i++) {ans.add(matrix[row][column]);int nextRow = row + moveDirections[directionIndex][0], nextColumn = column + moveDirections[directionIndex][1];if (nextRow < top || nextRow > bottom || nextColumn < left || nextColumn > right) {// 变换方向directionIndex = (directionIndex + 1) % 4;// 修改边界left += borderDirections[directionIndex][0];right += borderDirections[directionIndex][1];top += borderDirections[directionIndex][2];bottom += borderDirections[directionIndex][3];}row += moveDirections[directionIndex][0];column += moveDirections[directionIndex][1];}return ans;}
}

每次循环完成一个顺时针:

class Solution {public List<Integer> spiralOrder(int[][] matrix) {List<Integer> ans = new ArrayList<Integer>();final int rows = matrix.length, columns = matrix[0].length;int       left = 0, right = columns - 1, top = 0, bottom = rows - 1;while (left <= right && top <= bottom) {for (int column = left; column <= right; ++column) {ans.add(matrix[top][column]);}for (int row = top + 1; row <= bottom; ++row) {ans.add(matrix[row][right]);}if (left < right && top < bottom) {for (int column = right - 1; column >= left; --column) {ans.add(matrix[bottom][column]);}for (int row = bottom - 1; row > top; --row) {ans.add(matrix[row][left]);}}++left;--right;++top;--bottom;}return ans;}
}

非常感谢你阅读本文~
欢迎【点赞】【收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~


http://www.lryc.cn/news/92641.html

相关文章:

  • 单容水箱建模(自衡单容水箱+无自衡单容水箱)
  • 分享Python7个爬虫小案例(附源码)
  • 我用ChatGPT写2023高考语文作文(一):全国甲卷
  • c++ modbusTCP
  • linux(信号结尾)
  • 【漏洞修复】node-exporter被检测出来pprof调试信息泄露漏洞
  • 在linux 上安装 NFS服务器软件
  • 网卡中的Ring buffer -- 解决 rx_resource_errors 丢包
  • 六月九号补题日记:Codeforces Round 877 (Div. 2)
  • python基础选择题,高中适用
  • Linux 面试题-(腾讯,百度,美团,滴滴)
  • DDD--战略设计步骤
  • Web Scoket简述
  • “Docker 技术在企业中的应用及挑战解决方案“
  • vue中开发包、生产包、全局包的区别以及安装语法
  • list的模拟实现
  • ChatGLM简介和SSE聊天接口测试效果
  • darknet yolo标注、训练详细说明
  • chatgpt赋能python:Python如何产生随机整数?
  • 大话Stable-Diffusion-Webui-客制化主题(四)
  • Excel函数VLOOKUP常用方法
  • systemV的工作原理+原理代码
  • Kubeflow--TFJob实现机制学习
  • 百度出品,Nature重磅 -- 优化的mRNA设计算法可改善mRNA的稳定性和免疫原性
  • CKA 01_docker部署Kubernetes 部署docker 使用kubeadm引导集群 安装Pod网络
  • Redis的使用规范小建议
  • 操作受限的线性表——栈
  • C++基类指针或引用指向或引用派生类对象(实现动态多态四种手段)父类指针访问子类成员变量(需要dynamic_cast)
  • WTM框架运行报错0308010C:digital envelope routines::unsupported
  • (二)CSharp-索引器