LeetCode_48---Rotate Image

来源:互联网 发布:工具开发程序员 编辑:程序博客网 时间:2024/06/05 10:05

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?

Hide Tags
 Array
翻转图像,在CTCI见过这个题目。




Code:


/** *  */package From41;/** * @author MohnSnow * @time 2015年6月24日 下午4:50:04 *  */public class LeetCode48 {/** * @param argsmengdx *            -fnst *///304msAC---一次性通过public static void rotate(int[][] matrix) {int len = matrix.length;int temp;for (int i = 0; i < len / 2; i++) {//分len/2层for (int j = i; j < len - i - 1; j++) {temp = matrix[i][j];//matrix[i][j] = matrix[len - j - 1][i];matrix[len - j - 1][i] = matrix[len - i - 1][len - j - 1];matrix[len - i - 1][len - j - 1] = matrix[j][len - i - 1];matrix[j][len - i - 1] = temp;}}return;}public static void main(String[] args) {int[][] matrix = {{ 1, 1, 1, 1 },{ 2, 2, 2, 2 },{ 3, 3, 3, 3 },{ 4, 4, 4, 4 },};rotate(matrix);for (int i = 0; i < matrix.length; i++) {for (int j = 0; j < matrix.length; j++) {System.out.print(" " + matrix[i][j]);}System.out.println("");}}}



0 0
原创粉丝点击