File tree 2 files changed +38
-0
lines changed
2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change 32
32
| 35| [ 搜索插入位置] ( https://leetcode.cn/problems/search-insert-position/ ) | [ JavaScript] ( ./algorithms/search-insert-position.js ) | Easy|
33
33
| 48| [ 旋转图像] ( https://leetcode.cn/problems/rotate-image/ ) | [ JavaScript] ( ./algorithms/rotate-image.js ) | Medium|
34
34
| 49| [ 字母异位词分组] ( https://leetcode.cn/problems/group-anagrams/ ) | [ JavaScript] ( ./algorithms/group-anagrams.js ) | Medium|
35
+ | 54| [ 螺旋矩阵] ( https://leetcode.cn/problems/spiral-matrix/ ) | [ JavaScript] ( ./algorithms/spiral-matrix.js ) | Medium|
35
36
| 58| [ 最后一个单词的长度] ( https://leetcode.cn/problems/length-of-last-word/ ) | [ JavaScript] ( ./algorithms/length-of-last-word.js ) | Easy|
36
37
| 59| [ 螺旋矩阵 II] ( https://leetcode.cn/problems/spiral-matrix-ii/ ) | [ JavaScript] ( ./algorithms/spiral-matrix-ii.js ) | Medium|
37
38
| 53| [ 最大子数组和] ( https://leetcode.cn/problems/maximum-subarray/ ) | [ JavaScript] ( ./algorithms/maximum-subarray.js ) | Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 54. 螺旋矩阵
3
+ * 参考: https://leetcode.cn/problems/spiral-matrix/solution/cxiang-xi-ti-jie-by-youlookdeliciousc-3/
4
+ * @param {number[][] } matrix
5
+ * @return {number[] }
6
+ */
7
+ var spiralOrder = function ( matrix ) {
8
+ if ( matrix . length === 0 ) return [ ] ;
9
+
10
+ // 赋值上下左右边界
11
+ let left = 0 ,
12
+ top = 0 ;
13
+ let right = matrix [ 0 ] . length - 1 ;
14
+ let bottom = matrix . length - 1 ;
15
+ let result = [ ] ;
16
+
17
+ while ( true ) {
18
+ // 从左到右
19
+ for ( let i = left ; i <= right ; i ++ ) result . push ( matrix [ top ] [ i ] ) ;
20
+ // 重新设定上边界. 若上边界大于下边界,则遍历完成,下同
21
+ if ( ++ top > bottom ) break ;
22
+
23
+ // 从上到下
24
+ for ( let i = top ; i <= bottom ; i ++ ) result . push ( matrix [ i ] [ right ] ) ;
25
+ if ( -- right < left ) break ;
26
+
27
+ // 从右到左
28
+ for ( let i = right ; i >= left ; i -- ) result . push ( matrix [ bottom ] [ i ] ) ;
29
+ if ( -- bottom < top ) break ;
30
+
31
+ // 从下到上
32
+ for ( let i = bottom ; i >= top ; i -- ) result . push ( matrix [ i ] [ left ] ) ;
33
+ if ( ++ left > right ) break ;
34
+ }
35
+
36
+ return result ;
37
+ } ;
You can’t perform that action at this time.
0 commit comments