首页 > 其他 > 详细

LeetCode-48-Rotate Image

时间:2015-09-08 02:05:07      阅读:281      评论:0      收藏:0      [点我收藏+]

Rotate Image

?

?

来自 <https://leetcode.com/problems/rotate-image/>

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?n2D矩阵代表一张图片,将图片旋转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;
			}
		}
    }
}

代码性能


bubuko.com,布布扣
?

LeetCode-48-Rotate Image

原文:http://972459637-qq-com.iteye.com/blog/2241480

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!