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

news2025/2/26 3:34:44

文章目录

  • 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-1
	ans := make([]int, rows*columns)
	index := 0

	for 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 - 1
        while 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 - 1
        return 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.coloradmin.cn/o/618866.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

玩转 GPT4All

目录 什么是Chatgpt 什么是gpt4all 如何使用 第一步&#xff1a;下载LLM模型 第二步&#xff1a;下载代码 第三步&#xff1a;将模型替换到 第四步&#xff1a;执行启动命令 第五步&#xff1a;生成自己的客户端 第六步&#xff1a;启动 第七步&#xff1a;配置UI 什么…

【CesiumJS入门】(3)ImageryLayer之图层卷帘

前言 上一篇博客简单得介绍了影像图层并成功在视图上加载出来了&#xff0c;而今天我们来实现一个简单的可视化效果&#xff0c;影像图层卷帘。 前置知识&#xff1a;Cesium 事件详解&#xff08;鼠标事件、相机事件、键盘事件、场景触发事件&#xff09;_cesium点击事件_GIS…

OPT CST 慕藤光

OPT 波特率 数据长度 停止位 奇偶校验 9600 bps 8 bits 1 bit 无 所有通讯字节都采用ASCII码 特征字 &#xff1d; $命令字 &#xff1d; 1&#xff0c;2&#xff0c;3&#xff0c;4 打开对应通道电源关闭对应通道电源设置对应通道电源参数读出对应通道电…

【论文阅读】Twin Neural Network Regression

论文下载 GitHub bib: ARTICLE{SebastianKevin2022Twin,title {Twin neural network regression},author {Sebastian Johann Wetzel and Kevin Ryczko and Roger Gordon Melko and Isaac Tamblyn},journal {Applied AI Letters},year {2022},volume {3},number …

SpringBoot整合邮箱验证码实现用户注册

唠嗑部分 今天我们来分享一下在系统开发过程中&#xff0c;如何使用验证码来验证用户并完成用户注册 首先来看一下成品界面展示 说一下以上注册功能的设计&#xff1a; 用户手动输入用户名(全数据库唯一)、密码、确认密码、邮箱地址(单个邮箱最多可注册3个用户)、正确的邮箱…

Arm 推出 2023 全面计算解决方案,加速终端 AI 应用开发和部署

在当今数字化时代&#xff0c;人们对移动端计算能力的要求已经上升到了前所未有的高度。他们需要移动设备具有更快、更先进、更持久的计算能力&#xff0c;以提高生产力和生活质量。而科技厂商在满足人们对移动端计算能力的需求的同时&#xff0c;还需要从整个生态系统的角度出…

通过python封装接口seller_nick获取京东店铺所有商品数据,京东店铺所有商品数据接口,京东API接口

目的&#xff1a; 通过python封装接口seller_nick获取京东店铺所有商品数据&#xff0c;方法如下&#xff1a; 使用京东开放平台提供的API接口文档&#xff0c;找到seller_nick接口的具体参数及请求方式。 使用Python中的requests库发送请求&#xff0c;获取接口返回的数据。 …

nuxt3.0学习-三、nuxt.config.ts配置、跨域处理以及浏览器适配处理

nuxt官方对于nuxt.config.ts配置的介绍在Nuxt3.0 nuxt.config.ts配置 关于如何配置本人只能给出一点点启发&#xff0c;具体的配置需要根据个人需求去配置 nuxt.config.ts配置、跨域处理 import { prismjsPlugin } from "vite-plugin-prismjs"; export default de…

CompletableFuture异步和线程池

一、线程回顾 1、初始化线程的 4 种方式 1&#xff09;、继承 Thread 2&#xff09;、实现 Runnable 接口 3&#xff09;、实现 Callable 接口 FutureTask &#xff08;可以拿到返回结果&#xff0c;可以处理异常&#xff09; 4&#xff09;、线程池 方式 1 和方式 2&am…

《精通特征工程》学习笔记(1):数值特征处理

不进行多余的解释&#xff0c;想看原文直接下载pdf查看&#xff0c;本文是精简提炼了重要的方法写进来。 1.二值化 在百万歌曲数据集中&#xff0c;原始的收听次数并不是衡量用户喜好的强壮指标。&#xff08;在统计学术语 中&#xff0c;“强壮”意味着该方法适用于各种情况…

【2611. 老鼠和奶酪】

来源&#xff1a;力扣&#xff08;LeetCode&#xff09; 描述&#xff1a; 有两只老鼠和 n 块不同类型的奶酪&#xff0c;每块奶酪都只能被其中一只老鼠吃掉。 下标为 i 处的奶酪被吃掉的得分为&#xff1a; 如果第一只老鼠吃掉&#xff0c;则得分为 reward1[i] 。如果第二…

Hive之HPLSQL安装手册

软件版本信息&#xff1a; CDH&#xff1a; cdh5.14.0 Hive: 1.1.0 Impala&#xff1a;2.11.0一&#xff1a;下载地址 Hplsql官网&#xff1a; http:www.hplsql.org/download 下载的是&#xff1a;hplsql-0.3.31.tar.gz版本 二&#xff1a;安装步骤 解压下载的hplsql-0.3.…

kafka 02

4.API开发 准备&#xff1a; 创建项目 &#xff0c; 添加依赖 XML <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <depen…

如何评价编程语言 Reason?

Reason编程语言的设计目标是为开发人员提供一种易于理解和学习的工具&#xff0c;同时提供静态类型检查和高效的代码执行。Reason基于OCaml语言&#xff0c;并引入了JavaScript的语法和工具链&#xff0c;使得开发者能够在现有的JavaScript生态系统中更好地开发和维护代码。Rea…

2023,数据库国产替代走到哪了?

如今&#xff0c;战场不仅银行&#xff0c;参战者也不仅单独的一家。对中国的国产数据库而言&#xff0c;机会和挑战都在加速涌来。 作者|思杭 编辑|皮爷 出品|产业家 2023&#xff0c;数据库格局正在变化&#xff0c;愈演愈烈。 如果说哪个环节是如今国产替代的最火热…

chatgpt赋能python:Python中如何输出两个数

Python中如何输出两个数 对于任何一种编程语言来说&#xff0c;输出两个数都是非常基础的知识点&#xff0c;Python也不例外。在Python中&#xff0c;我们可以使用print()函数来输出两个数。本篇文章将会介绍如何在Python中输出两个数。 介绍 在Python中&#xff0c;输出两个…

Python让文档处理变得轻松:如何快速替换Word文档中的关键字

应用场景&#xff1a; Python自动化处理Word文档的功能可以应用于许多场景&#xff0c;以下是其中一些常见的应用场景&#xff1a; 批量处理文档&#xff1a;如果您需要处理大量的Word文档&#xff0c;例如替换文本、添加文本、修改格式等&#xff0c;手动完成这些任务将非常耗…

驱动LSM6DS3TR-C实现高效运动检测与数据采集(4)----上报匿名上位机实现可视化

概述 LSM6DS3TR-C是单芯片“3轴陀螺仪 3轴加速度计”的惯性 测量单元(IMU)&#xff0c; 五种种可选满量程的陀螺仪(125/250/500/1000/2000 dps)和加速度计(2/4/8/16 g)。 上述工程中选择的加速度和陀螺仪对应的量程为2g和2000dps&#xff0c;对应的灵敏度如下所示&#xff0c…

具有更多存储空间和带宽的亚马逊云科技Snowball Edge存储优化型设备

亚马逊云科技AWS Snow Family系列设备用于将数据经济高效地迁移到云端并在边缘进行处理。增强型Snowball Edge存储优化型设备专为PB级数据迁移项目而设计&#xff0c;具有210TB的NVMe存储空间&#xff0c;每秒可传输高达1.5千兆字节的数据。这些设备还包括10GBASE-T、SFP48和QS…

缩略图加密学习总结

一、缩略图加密概述 完全加密为噪声图像后&#xff0c;密文图像的文件扩展&#xff0c;传输存储消耗更多的资源。完全加密的噪声图像的可用性建立在对密文进行解密的基础上&#xff0c;耗费大量的计算代价。原始图像中精细的视觉信息被抹去以保护隐私,而粗略的视觉信息被保留以…