「力扣」第 48 题:旋转图像(数组)

地址:https://leetcode-cn.com/problems/rotate-image/

方法一:先转置,再逐行反转

在这里插入图片描述

Java 代码:

import java.util.Arrays;

public class Solution {

    public void rotate(int[][] matrix) {
        int N = matrix.length;

        // 第 1 步:转置
        for (int i = 0; i < N; i++) {
            for (int j = i + 1; j < N; j++) {
                swap(matrix, i, j);
            }
        }

        // 第 2 步:逐行反转
        for (int[] row : matrix) {
            reverse(row, N);
        }
    }

    /**
     * 将坐标 (x, y) 与 坐标 (y, x) 互换
     *
     * @param matrix
     * @param x
     * @param y
     */
    private void swap(int[][] matrix, int x, int y) {
        int temp = matrix[x][y];
        matrix[x][y] = matrix[y][x];
        matrix[y][x] = temp;
    }

    private void reverse(int[] arr, int N) {
        int left = 0;
        int right = N - 1;
        while (left < right) {

            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;

            left++;
            right--;
        }
    }

    public static void main(String[] args) {
        int[][] matrix = {
                {5, 1, 9, 11},
                {2, 4, 8, 10},
                {13, 3, 6, 7},
                {15, 14, 12, 16}
        };

        Solution solution = new Solution();
        solution.rotate(matrix);

        for (int[] row : matrix) {
            System.out.println(Arrays.toString(row));
        }
    }
}

方法二: 4 个位置的数轮着转

在这里插入图片描述

Java 代码:

import java.util.Arrays;

public class Solution2 {

    // 4 个数轮换,大风车转呀转悠悠

    public void rotate(int[][] matrix) {
        int N = matrix.length;
        for (int i = 0; i < N / 2; i++) {
            for (int j = i; j < N - i - 1; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[N - j - 1][i];
                matrix[N - j - 1][i] = matrix[N - i - 1][N - j - 1];
                matrix[N - i - 1][N - j - 1] = matrix[j][N - i - 1];
                matrix[j][N - i - 1] = temp;
            }
        }
    }

    public static void main(String[] args) {
        int[][] matrix = {
                {5, 1, 9, 11},
                {2, 4, 8, 10},
                {13, 3, 6, 7},
                {15, 14, 12, 16}
        };

        Solution2 solution2 = new Solution2();
        solution2.rotate(matrix);

        for (int[] row : matrix) {
            System.out.println(Arrays.toString(row));
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值