王海鱼 发表于 2025-10-27 20:45:09

矩阵-旋转图像

旋转图像
给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。

你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。
输入:二维数组
输出:void
思绪:tempMatrix = matrix
class Solution {
    public void rotate(int[][] matrix) {
      //二维数组为n*n的方阵
      int n = matrix.length;
      // 使用辅助数组
      int[][] tempMatrix = new int;
      for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                tempMatrix = matrix;
            }
      }
      for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                matrix = tempMatrix;
            }
      }
    }
}
但是原题分析不能使用别的一个数组来旋转图像,以是使用新方法
class Solution {
    public void rotate(int[][] matrix) {
      //二维数组为n*n的方阵
      int n = matrix.length;
      //保证不重复不遗漏
      for(int i = 0; i < n / 2; i++){
            //j
            for(int j = 0; j < (n + 1) / 2; j++){
                int temp = matrix;
                matrix = matrix;
                matrix = matrix;
                matrix = matrix;
                matrix = temp;
            }
      }
    }
}
https://i-blog.csdnimg.cn/direct/755d0fdc4a9544149e42e0728f08f5de.png
图中四个位置的值更换,可以使用temp变量暂时存储,使用两数互换的方法举行四个数互换
关键在于为了使互换不重复和不遗漏,留意代码中i和j的上限值
https://i-blog.csdnimg.cn/direct/2344a0d2aafa49e58042669533825c78.png
https://i-blog.csdnimg.cn/direct/d23bfe2ec46449048867dffab4fdd3e0.png
二刷使用新方法:
用翻转取代旋转
https://i-blog.csdnimg.cn/direct/680e5f6b2353459ab2c981e5dd59c4be.png
class Solution {
    public void rotate(int[][] matrix) {
      int n = matrix.length;
      for(int i = 0; i < n / 2; i++){
            for(int j = 0; j < n; j++){
                //上下水平翻转
                int temp = matrix;
                matrix = matrix;
                matrix = temp;
            }
      }
      for(int i = 0; i < n; i++){
            for(int j=0; j < i; j++){
                //主对角线翻转
                int temp = matrix;
                matrix = matrix;
                matrix = temp;
            }
      }
    }
}

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 矩阵-旋转图像