LeetCode | 48. Rotate Image

48. Rotate Image

Description

描述:https://leetcode.com/problems/rotate-image/description/
题意:将一个矩阵(二维数组)顺时针旋转90度,不能分配额外的二维空间。

Solution: (Java)
class Solution {
    public void rotate(int[][] matrix) {
        int start_index = 0;
        int n = matrix[0].length;
        int j_max = n - 2;
        int i_max = n/2 - 1;
        int temp, current, temp_i, temp_j, temp_k;
        for (int i = 0; i <= i_max; i++) {
            for (int j = start_index; j <= j_max; j++) {
                current = matrix[i][j];
                temp_i = i;
                temp_j = j;
                for (int k = 0; k < 4; k++) {
                    temp = matrix[temp_j][n-1-temp_i];
                    matrix[temp_j][n-1-temp_i] = current;
                    current = temp;
                    temp_k = temp_i;
                    temp_i = temp_j;
                    temp_j = n-1-temp_k;

                }
            }
            start_index = start_index + 1;
            j_max = j_max - 1;
        }
    }
}
思路
  • 找到每个坐标的变换规律即可,即 matrix[i][j]的值旋转90度之后,会变换到matrix[j][n-1-i]这个位置;
  • 每个位置会与其他3个值互相影响,所以中间有个4次的循环;
  • 其他要注意的就是编程的处理了,保证每个位置只遍历一遍,注意循环的边界变化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值