面试题6 将一个n*n图像矩阵顺时针旋转90°

题目: 用一个 n*n 的 int 矩阵代表一个图像 原址将这个图像旋转九十度

思路: 先将所有行倒序  就是第一行变成最后一行 然后第二行变成倒数第二行 以此类推 然后根据对角线将对称的位置对换  就可以了 代码如下

  public void mySolution(int[][] image){
    if(!isSquareMatrix(image))  return;

    int n = image.length; //n is the size of the square matrix

    //reverse the matrix by row (so first row become the last and so on)
    for(int i=0, j=n-1; i<j; i++, j--){
      int[] temp = image[i];
      image[i] = image[j];
      image[j] = temp;
    }

    //swap entries against diagonal
    for(int i=0; i<n-1; i++){
      for(int j=i+1; j<n; j++)  swap(image, j,i, i,j);
    }

  private void swap(int[][] a, int row1, int col1, int row2, int col2){
    int temp = a[row1][col1];
    a[row1][col1] = a[row2][col2];
    a[row2][col2] = temp;
  }

该方法的时间复杂度和空间复杂度均为 O(n) 

 

另一种思路: 由最外层开始一层一层旋转九十度 将上面的变成对应位置右面的 将对应位置右面的变成下面 以此类推 代码如下

  public void goodSolution(int[][] matrix){
    if(!isSquareMatrix(matrix)) return;

    int n = matrix.length;

    for(int layer=0; layer<n/2; ++layer){
      int first = layer;
      int last = n-layer-1;

      for(int i=first; i<last; ++i){
        int offset = i-first;
        
        int top = matrix[first][i];
        matrix[first][i] = matrix[last-offset][first];
        matrix[last-offset][first] = matrix[last][last-offset];
        matrix[last][last-offset] = matrix[i][last];
        matrix[i][last] = top;
      }
    }
  }

该方法更难思考一些 但是效率最高 时间复杂度和空间复杂度也均为 O(n)

转载于:https://www.cnblogs.com/moechen/p/5077419.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值