0
点赞
收藏
分享

微信扫一扫

【Leetcode】Rotate Image

梅梅的时光 2023-07-26 阅读 50


题目链接:https://leetcode.com/problems/rotate-image/

题目:

n x n

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

思路:

先将矩阵转置,再将矩阵按中轴线对称交换每一列。

算法:

public void rotate(int[][] matrix) {
		for (int i = 0; i < matrix.length; i++) { //转置
			for (int j = i; j < matrix[0].length; j++) {
				int tmp = matrix[i][j];
				matrix[i][j] = matrix[j][i];
				matrix[j][i] = tmp;
			}
		}
		for (int i = 0; i < matrix.length; i++) {//交换列
			for (int j = 0; j < matrix[0].length / 2; j++) {
				int tmp = matrix[i][j];
				matrix[i][j] = matrix[i][matrix[0].length - 1 - j];
				matrix[i][matrix[0].length - 1 - j] = tmp;
			}
		}
	}




举报

相关推荐

0 条评论