自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

每日算法:螺旋矩陣

開發(fā) 前端 算法
給定一個(gè)正整數(shù) n,生成一個(gè)包含 1 到 n2 所有元素,且元素按順時(shí)針順序螺旋排列的正方形矩陣。

[[431971]]

本文轉(zhuǎn)載自微信公眾號(hào)「三分鐘學(xué)前端」,作者sisterAn  。轉(zhuǎn)載本文請(qǐng)聯(lián)系三分鐘學(xué)前端公眾號(hào)。

給定一個(gè)正整數(shù) n,生成一個(gè)包含 1 到 n2 所有元素,且元素按順時(shí)針順序螺旋排列的正方形矩陣。

示例:

  1. 輸入: 3 
  2. 輸出: 
  3.  [ 1, 2, 3 ], 
  4.  [ 8, 9, 4 ], 
  5.  [ 7, 6, 5 ] 

解答

  1. const generateMatrix = (n) => { 
  2.     // 定義一個(gè)二維數(shù)組進(jìn)行數(shù)據(jù)保存 
  3.     const result = [] 
  4.     for (let i = 0; i < n; i++) { 
  5.         result.push(new Array(n)) 
  6.     } 
  7.     let left = 0 
  8.     let right = n - 1 
  9.     let top = 0 
  10.     let bottom = n - 1 
  11.     let current = 1, max = n * n 
  12.     while(current <= max) { 
  13.         // 上面從左到右 
  14.         for (let i = left; i <= right; i++) { 
  15.             result[top][i] = current++ 
  16.         } 
  17.         top ++ 
  18.         // 右邊從上到下 
  19.         for (let i = top; i <= bottom; i++) { 
  20.             result[i][right] = current++ 
  21.         } 
  22.         right -- 
  23.         // 下邊從右到左 
  24.         for (let i = right; i >= left; i--) { 
  25.             result[bottom][i] = current++ 
  26.         } 
  27.         bottom -- 
  28.         // 左邊從下到上 
  29.         for (let i = bottom; i >= top; i--) { 
  30.             result[i][left] = current++ 
  31.         } 
  32.         left ++ 
  33.     } 
  34.     return result 

 

leetcode:https://leetcode-cn.com/problems/spiral-matrix-ii

 

責(zé)任編輯:武曉燕 來源: 三分鐘學(xué)前端
相關(guān)推薦

2021-10-28 19:33:36

矩陣圖像內(nèi)存

2021-08-30 14:34:10

有效算法字符

2021-11-19 07:54:40

前端

2021-11-12 09:44:03

字符串算法復(fù)雜度

2021-09-30 09:58:14

路徑總和二叉樹

2021-11-04 09:59:03

動(dòng)態(tài)規(guī)劃策略

2021-09-03 09:41:36

字符串時(shí)間復(fù)雜度

2021-10-26 00:23:26

算法高頻元素

2017-02-08 09:25:16

Spark分解推薦

2021-10-27 10:43:36

數(shù)據(jù)流中位數(shù)偶數(shù)

2021-09-29 10:19:00

算法平衡二叉樹

2021-09-02 09:22:13

算法無重復(fù)字符

2021-09-08 09:52:34

語言

2021-09-10 08:31:54

翻轉(zhuǎn)字符串單詞

2021-09-15 07:56:32

二叉樹層次遍歷

2021-09-28 06:28:51

二叉樹公共祖先

2021-10-19 10:09:21

三角形個(gè)數(shù)數(shù)組

2024-07-16 12:54:40

2023-02-15 09:00:00

算法推薦系統(tǒng)矩陣分解算法

2021-08-26 05:08:25

相鄰重復(fù)項(xiàng)算法
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)