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

这篇具有很好参考价值的文章主要介绍了算法leetcode|54. 螺旋矩阵(rust重拳出击)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。



54. 螺旋矩阵:

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

样例 1:

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

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

样例 2:

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

输入:
	
	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次方向,也就是完成一次顺时针,然后缩圈。
  • 把握换方向的边界是关键。
  • 边界缩小的时机也是关键。
  • 整体是一个由外向内的过程,边界值可以作为一个方向的最后一个值,也可以作为下一个方向的开始值,但是要注意不能重复。

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


题解:

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/ 博客原创~文章来源地址https://www.toymoban.com/news/detail-482492.html


到了这里,关于算法leetcode|54. 螺旋矩阵(rust重拳出击)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 算法leetcode|79. 单词搜索(rust重拳出击)

    给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

    2024年02月09日
    浏览(44)
  • 算法leetcode|72. 编辑距离(rust重拳出击)

    给你两个单词 word1 和 word2 , 请返回将 word1 转换成 word2 所使用的最少操作数 。 你可以对一个单词进行如下三种操作: 插入一个字符 删除一个字符 替换一个字符 0 = word1.length, word2.length = 500 word1 和 word2 由小写英文字母组成 面对这道算法题目,二当家的再次陷入了沉思。 编

    2024年02月12日
    浏览(30)
  • 算法leetcode|62. 不同路径(rust重拳出击)

    一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Finish” )。 问总共有多少条不同的路径? 1 = m, n = 100 题目数据保证答案小于等于 2 * 10 9 面对这道算法

    2024年02月17日
    浏览(28)
  • 算法leetcode|75. 颜色分类(rust重拳出击)

    给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums , 原地 对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 我们使用整数 0 、 1 和 2 分别表示红色、白色和蓝色。 必须在不使用库内置的 sort 函数的情况下解决这个问题。 n == nums.length

    2024年02月10日
    浏览(28)
  • 算法leetcode|55. 跳跃游戏(rust重拳出击)

    给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。 数组中的每个元素代表你在该位置可以跳跃的最大长度。 判断你是否能够到达最后一个下标。 1 = nums.length = 3 * 10 4 0 = nums[i] = 10 5 面对这道算法题目,二当家的再次陷入了沉思。 可能想到要暴力尝试或者是双循环

    2024年02月08日
    浏览(65)
  • 算法leetcode|65. 有效数字(rust重拳出击)

    有效数字 (按顺序)可以分成以下几个部分: 一个 小数 或者 整数 (可选)一个 \\\'e\\\' 或 \\\'E\\\' ,后面跟着一个 整数 小数 (按顺序)可以分成以下几个部分: (可选)一个符号字符( \\\'+\\\' 或 \\\'-\\\' ) 下述格式之一: 至少一位数字,后面跟着一个点 \\\'.\\\' 至少一位数字,后面跟着一个

    2024年02月15日
    浏览(30)
  • 算法leetcode|89. 格雷编码(rust重拳出击)

    n 位格雷码序列 是一个由 2 n 个整数组成的序列,其中: 每个整数都在范围 [0, 2 n - 1] 内(含 0 和 2 n - 1) 第一个整数是 0 一个整数在序列中出现 不超过一次 每对 相邻 整数的二进制表示 恰好一位不同 ,且 第一个 和 最后一个 整数的二进制表示 恰好一位不同 给你一个整数

    2024年02月04日
    浏览(38)
  • 算法leetcode|48. 旋转图像(rust重拳出击)

    给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。 你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。 请不要 使用另一个矩阵来旋转图像。 n == matrix.length == matrix[i].length 1 = n = 20 -1000 = matrix[i][j] = 1000 面对这道算法题目,二当家

    2024年02月01日
    浏览(61)
  • 算法leetcode|85. 最大矩形(rust重拳出击)

    给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。 rows == matrix.length cols == matrix[0].length 1 = row, cols = 200 matrix[i][j] 为 ‘0’ 或 ‘1’ 面对这道算法题目,二当家的再次陷入了沉思。 要不是刚做过 84. 柱状图中最大的矩形 这

    2024年02月08日
    浏览(37)
  • 算法leetcode|60. 排列序列(rust重拳出击)

    给出集合 [1,2,3,...,n] ,其所有元素共有 n! 种排列。 按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下: \\\"123\\\" \\\"132\\\" \\\"213\\\" \\\"231\\\" \\\"312\\\" \\\"321\\\" 给定 n 和 k ,返回第 k 个排列。 1 = n = 9 1 = k = n! 面对这道算法题目,二当家的再次陷入了沉思。 如果模拟,按顺序生成k个

    2024年02月12日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包