三天一题-34- Rotate Image

题目地址: Rotate Image
描述:
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
大致意思:给一个由二维数组组成的正方形,求旋转90度后的组合。要求:原地旋转(不能使用其他的二维数据空间);

在这里插入图片描述

基本思想:从左上角的点开始循环,i=1;首先1,1,14,14四个点,顺时针交换,i=2;是4,2,14,2,顺时针再交换;i
=3; 7,3,14,3,顺时针交换;i=4;7,12,10,2顺时针交换;接着是进入迭代,迭代就是第二次正方形,如图所示,然后进行和上面一样的for循环操作。

public class RotateImage {
    public static void main(String[] args) {
        int[][] arr = { { {1,4,7,7,1},{2,5,8,8,2},{3,6,9,9,3},{12,9,11,11,12},{14,10,14,14,14}}};
        rotate(arr);
        System.out.println(Arrays.toString(arr));
    }
    private static void rotate(int[][] matrix){
        int length = matrix.length;
        iteration(matrix,length,0);
    }
    //先是最外层,然后迭代每一层。
    private static void iteration(int[][] matrix, int len, int index) {
        if (len - index < 2) {
            return;
        }
        int j = len -1;
        int temp, tem;
        //循环交换每一层的数字
        for (int i = 0; i+index < j; i++) {
            temp = matrix[i+index][j];
            matrix[i+index][j] = matrix[index][i+index];
            tem = matrix[j][len - i-1];
            matrix[j][len - i-1] = temp;
            temp = matrix[j-i][index];
            matrix[j-i][index] = tem;
            matrix[index][i+index] = temp;
        }
        iteration(matrix,len-1,++index);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值