Make writing a habit together! This is the fourth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.
preface
Our community will continue to include Yi Gu (Netflix growth hacker, author of The Way to Interview for iOS, ACE professional fitness coach). Swift algorithm problem solving sorted into text version to facilitate everyone to learn and read.
So far, we have updated 58 issues of LeetCode algorithm, and we will keep the update time and progress (Monday, Wednesday, Friday 9:00 am release). The content of each issue is not much, we hope you can read it on your way to work, there will be a great improvement in long-term accumulation.
Short step, no thousands of miles; No small streams, no rivers and seas, Swift community with you forward. If you have suggestions and comments welcome to leave a message at the end of the article, we will try our best to meet your needs.
Difficulty level: Medium
1. Describe
Given a positive integer n, generate an n x n square matrix matrix containing all elements from 1 to n2 in a clockwise spiral order.
Example 2.
Example 1
Input: n = 3 output: [[1,2,3],[8,9,4],[7,6,5]]Copy the code
Example 2
Input: n = 1 Output: [[1]]Copy the code
Constraints:
1 <= n <= 20
3. The answer
class SpiralMatrixII {
func generateMatrix(_ n: Int)- > [[Int]] {
guard n > 0 else {
return [[Int]]()
}
var num = 1
var res = Array(repeating: Array(repeating: 0, count: n), count: n)
for layer in 0..<n / 2 {
let start = layer
let end = n - layer - 1
// top
for i in start..<end {
res[start][i] = num
num + = 1
}
// right
for i in start..<end {
res[i][end] = num
num + = 1
}
// bottom
for i in stride(from: end, to: start, by: -1) {
res[end][i] = num
num + = 1
}
// left
for i in stride(from: end, to: start, by: -1) {
res[i][start] = num
num + = 1}}// handle the center one
if n % 2 ! = 0 {
res[n / 2][n / 2] = n * n
}
return res
}
}
Copy the code
- Main idea: Start clockwise and fill in the numbers, remembering to work with the middle one.
- Time complexity: O(n^2)
- Space complexity: O(1)
Leetcode-swift is a repository for solving problems of this algorithm
Click to go to LeetCode practice
About us
We are jointly maintained by Swift enthusiasts. We will share technical content based on Swift combat, SwiftUI and Swift foundation, as well as collect excellent learning materials.