标签:
记得有道Amazon的OA题目,好像是给定一个矩阵,让把矩阵的每个元素向右shift一个位置。这道题之前没有好好自习想过。今天正好刷到了rotate matrix,所以正好一块想了。
思路是类似LeetCode Spiral Matrix:
Time Complexity - O(mn),Space Complexity - O(1), in place。
public class Solution { public void rotateMatrixByOne(int[][] matrix) { if (matrix == null || matrix[0] == null) { return; } int m = matrix.length; int n = matrix[0].length; int left = 0, top = 0, right = n - 1, bot = m - 1; int count = 0; int totalElements = m * n; while (count < totalElements) { int tmp = matrix[top][left]; if (count < totalElements) { for (int i = top; i < bot; i++) { matrix[i][left] = matrix[i + 1][left]; count++; } left++; } if (count < totalElements) { for (int i = left - 1; i < right; i++) { matrix[bot][i] = matrix[bot][i + 1]; count++; } bot--; } if (count < totalElements) { for (int i = bot + 1; i > top; i--) { matrix[i][right] = matrix[i - 1][right]; count++; } right--; } if (count < totalElements) { for (int i = right + 1; i > left; i--) { matrix[top][i] = matrix[top][i - 1]; count++; } if (count != totalElements - 1) { matrix[top][left] = tmp; } else if (totalElements % 2 == 0) { matrix[top][left] = tmp; } count++; top++; } } } }
标签:
原文地址:http://www.cnblogs.com/yrbbest/p/5165084.html