Skip to content

Latest commit

 

History

History
49 lines (41 loc) · 1.25 KB

48.md

File metadata and controls

49 lines (41 loc) · 1.25 KB

48. Rotate Image

给一个二维数组按顺时针旋转九十度

思路:需要熟练,先将矩阵沿着左下到右上的对角线翻转,再上下翻转,就可以实现顺时针旋转90度的效果

Python:

class Solution:
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        # 6 star, 
        # 参考: https://shenjie1993.gitbooks.io/leetcode-python/048%20Rotate%20Image.html
        n = len(matrix)
        for row in range(n):
            for column in range(n - row):
                matrix[row][column], matrix[n - 1 - column][n - 1 - row] = matrix[n - 1 - column][n - 1 - row], \
                                                                           matrix[row][column]
        matrix.reverse()

Go:

func rotate(matrix [][]int)  {
	var tempSlice []int
	var temp int
	cols := len(matrix)
	//rows := len(matrix[0])
	for index:=0; index < cols/2; index++ {
		tempSlice = matrix[index]
		matrix[index] = matrix[cols-1-index]
		matrix[cols-1-index] = tempSlice
	}
	for i:=0; i<cols; i++ {
		for j:=0; j< i; j++ {
			temp = matrix[i][j]
			matrix[i][j] = matrix[j][i]
			matrix[j][i] = temp
		}
	}

}