• 134-48. 旋转图像


    给定一个 n × n 的二维矩阵表示一个图像。将图像顺时针旋转 90 度。(这次没有抄,都是我写的)
    class Solution(object):
        def rotate1(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: None Do not return anything, modify matrix in-place instead.
            """
            length = len(matrix)
            data_list = ["0"] * (length ** 2)
            for i in range(length):
                for j in range(length):
                    # 其实最主要的就是这个计算first_index和second_index的过程
                    first_index = j   # 根据旋转90度退出j会变为i
                    second_index = abs(i-length + 1)  # i-数组长度的绝对值会变成j
    
                    data_list[first_index * length + second_index] = matrix[first_index][second_index]
    
                    if data_list[i * length + j] != "0":
                        exchange_num = data_list[i * length + j]
                    else:
                        exchange_num = matrix[i][j]
                    matrix[first_index][second_index] = exchange_num
    
        def rotate2(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: None Do not return anything, modify matrix in-place instead.
            """
            length = len(matrix)
            data_list = ["0"] * (length ** 2)
            for i in range(length):
                for j in range(length):
                    first_index = j
                    second_index = abs(i-length + 1)
    
                    data_list[first_index * length + second_index] = matrix[i][j]
    
            for i in range(length ** 2):
                i, j = divmod(i, length)
                matrix[i][j] = data_list[i * length + j]
    
        def rotate(self, matrix) -> None:
            n = len(matrix)
            # Python 这里不能 matrix_new = matrix 或 matrix_new = matrix[:] 因为是引用拷贝
            matrix_new = [[0] * n for _ in range(n)]
            for i in range(n):
                for j in range(n):
                    matrix_new[j][n - i - 1] = matrix[i][j]
            # 不能写成 matrix = matrix_new
            matrix[:] = matrix_new
    
    
    if __name__ == '__main__':
        s = Solution()
        matrix = [
            [1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]
        ]
        matrix = [
            [43,39,3,33,37,20,14],
            [9,18,9,-1,40,22,38],
            [14,42,3,23,12,14,32],
            [18,31,45,11,8,-1,31],
            [28,44,14,23,40,24,13],
            [29,45,33,45,20,0,45],
            [12,23,35,32,22,39,8]]
    
        matrix = [
            [5, 1, 9, 11],
            [2, 4, 8, 10],
            [13, 3, 6, 7],
            [15, 14, 12, 16]
        ]
    
  • 相关阅读:
    Linux命令比较文件内容
    Linux命令jobs小记
    权限控制框架
    Log4j2源码分析系列:(一)配置加载
    Callable和Supplier的区别
    排序算法之归并排序
    Spring boot整合Mybatis
    排序算法之堆排序
    排序算法之希尔排序
    排序算法之快速排序
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14252027.html
Copyright © 2020-2023  润新知