
题目描述
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?
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
public class Solution { 1 2 3 1 4 7 7 4 1 4 5 6 => 2 5 8 => 8 5 2 7 8 9 3 6 9 9 6 3 */ public void rotate(int[][] matrix) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return; int length = matrix.length; for(int i = 0; i < length; i++){ for(int j = i+1; j < length; j++){ int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } for(int i = 0; i < length; i++){ for(int j = 0; j < length/2; j++){ int temp = matrix[i][j]; matrix[i][j] = matrix[i][length-j-1]; matrix[i][length-j-1] = temp; } } } 1 2 3 1 4 7 3 6 9 4 5 6 => 2 5 8 => 2 5 8 7 8 9 3 6 9 1 4 7 */ public void rotate2(int[][] matrix){ if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return; int length = matrix.length; for(int i = 0; i < length; i++){ for(int j = i+1; j < length; j++){ int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } for(int i = 0; i < length/2; i++){ for(int j = 0; j < length; j++){ int temp = matrix[i][j]; matrix[i][j] = matrix[length-i-1][j]; matrix[length-i-1][j] = temp; } } } }
|
近期评论