题意:
解题思路:
思路:O(n2)。1. 定义四个方向:上右下左;2. 左上角开始遍历,走到右边最大值,改变方向往下走...,遍历完所有格子后退出;3. 我们填充时遍历一次矩阵,矩阵元素个数为 n2个,所以总时间复杂度是 O(n2);
PHP代码实现:
class Solution {/*** @param Integer $n* @return Integer[][]*/function generateMatrix($n) {$top = 0;$bottom = $n - 1;$left = 0; $right = $n - 1;$num = 1;$matrix = [];while ($top <= $bottom && $left <= $right) {for ($i = $left; $i <= $right; $i++) {$matrix[$top][$i] = $num++;}$top++;for ($i = $top; $i <= $bottom; $i++) {$matrix[$i][$right] = $num++;}$right--;for ($i = $right; $i >= $left; $i--) {$matrix[$bottom][$i] = $num++;}$bottom--;for ($i = $bottom; $i >= $top; $i--) {$matrix[$i][$left] = $num++;}$left++;}foreach ($matrix as $k => $v) {ksort($v);$matrix[$k] = $v;}return $matrix;}}
GO代码实现:
func generateMatrix(n int) [][]int {matrix := [][]int{}for i := 0; i < n; i++{matrix = append(matrix, make([]int, n))}size := n * ntop, bottom := 0, n-1 //左右边界left, right := 0, n-1 //上下边界idx := 1for idx <= size {//向右走for i := top; i <= bottom; i++ {matrix[left][i] = idxidx++}left++ //上边界收缩//向下走for i := left; i <= right; i++ {matrix[i][bottom] = idxidx++}bottom-- //右边界收缩for i := bottom;i >= top; i-- {matrix[right][i] = idxidx++}right--for i := right; i >= left; i-- {matrix[i][top] = idxidx++}top++}return matrix}
```
