classSolution { public: voidrotate(vector<vector<int>>& matrix){ int n = matrix.size(); int start = 0, end = n - 2; while(start <= end){ int i = start; for(int j = start; j <= end; ++j){ int cx = start, cy = j; int temp = matrix[cx][cy]; for(int k = 0; k < 3; ++k){ int nx = n - 1 - cy, ny = cx; matrix[cx][cy] = matrix[nx][ny]; cx = nx; cy = ny; } matrix[cx][cy] = temp; } ++start; end = n - 2 - start; } } };
C++ 思路2
1 2 3 4 5 6 7 8 9 10
classSolution { public: voidrotate(vector<vector<int> > &matrix){ int n = matrix.size(); for (int i = 0; i < n; i++) for (int j = 0; j < n - i - 1; j++) swap(matrix[i][j], matrix[n - j - 1][n - i - 1]); reverse(matrix.begin(), matrix.end()); } };
python 思路2
1 2 3 4 5 6 7 8 9 10 11
classSolution(object): defrotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ n = len(matrix) for i in range(len(matrix)): for j in range(len(matrix) - i - 1): matrix[i][j], matrix[n - j - 1][n - i - 1] = matrix[n - j - 1][n - i - 1], matrix[i][j] matrix.reverse()