---
title: "LeetCode-48-Rotate Image"
author: "随便小屋"
date: "2015-09-07T21:30:51Z"
tags: ["Array"]
categories: ["编程语言"]
slug: "leetcode-48-rotate-image"
draft: false
lastmod: "2015-09-07T21:31:45Z"
id: 2241480
url: "https://logicluo.iteye.com/blog/2241480"
---

Rotate Image

 

 

来自 &lt;[https://leetcode.com/problems/rotate-image/](https://leetcode.com/problems/rotate-image/)&gt;

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:

Could you do this in-place?

 

题目解读

给定一个n x n的2D矩阵代表一张图片，将图片旋转90度（顺时针方向）。

 

你能在原地解决吗？

 

解析：将二维矩阵先第0行与第n-1行、第1行与第n-2行…进行交换，然后按照主对角线进行交换。可得到旋转90°的效果

 

 

Java代码

```
public class Solution {
    public void rotate(int[][] matrix) {
        int low = 0;
		int high = matrix.length-1;
		int temp = 0;
		//第一次进行上下交换
		while(low<high) {
			for(int i=0; i<matrix.length; i++){
				temp = matrix[low][i];
				matrix[low][i] = matrix[high][i];
				matrix[high][i] = temp;
			}
			low++;
			high--;
		}
		
		//第二次按照主对角线进行交换
		for(int i=0; i< matrix.length; i++) {
			for(int j=i; j<matrix.length; j++) {
				temp = matrix[i][j];
				matrix[i][j] = matrix[j][i];
				matrix[j][i] = temp;
			}
		}
    }
}
```

代码性能

![](http://dl2.iteye.com/upload/attachment/0111/5081/2fb0d508-a9cf-3373-8275-02e5eaa7df96.png)