This commit is contained in:
krahets
2024-04-03 21:48:54 +08:00
parent d5a7899137
commit 0a9daa8b9f
11 changed files with 685 additions and 97 deletions
@@ -1080,9 +1080,24 @@ Note that memory occupied by initializing variables or calling functions in a lo
=== "Ruby"
```ruby title="space_complexity.rb"
[class]{}-[func]{function}
### 函数 ###
def function
# 执行某些操作
0
end
[class]{}-[func]{constant}
### 常数阶 ###
def constant(n)
# 常量、变量、对象占用 O(1) 空间
a = 0
nums = [0] * 10000
node = ListNode.new
# 循环中的变量占用 O(1) 空间
(0...n).each { c = 0 }
# 循环中的函数占用 O(1) 空间
(0...n).each { function }
end
```
=== "Zig"
@@ -1384,7 +1399,17 @@ Linear order is common in arrays, linked lists, stacks, queues, etc., where the
=== "Ruby"
```ruby title="space_complexity.rb"
[class]{}-[func]{linear}
### 线性阶 ###
def linear(n)
# 长度为 n 的列表占用 O(n) 空间
nums = Array.new(n, 0)
# 长度为 n 的哈希表占用 O(n) 空间
hmap = {}
for i in 0...n
hmap[i] = i.to_s
end
end
```
=== "Zig"
@@ -1566,7 +1591,12 @@ As shown below, this function's recursive depth is $n$, meaning there are $n$ in
=== "Ruby"
```ruby title="space_complexity.rb"
[class]{}-[func]{linear_recur}
### 线性阶(递归实现)###
def linear_recur(n)
puts "递归 n = #{n}"
return if n == 1
linear_recur(n - 1)
end
```
=== "Zig"
@@ -1806,7 +1836,11 @@ Quadratic order is common in matrices and graphs, where the number of elements i
=== "Ruby"
```ruby title="space_complexity.rb"
[class]{}-[func]{quadratic}
### 平方阶 ###
def quadratic(n)
# 二维列表占用 O(n^2) 空间
Array.new(n) { Array.new(n, 0) }
end
```
=== "Zig"
@@ -2001,7 +2035,14 @@ As shown below, the recursive depth of this function is $n$, and in each recursi
=== "Ruby"
```ruby title="space_complexity.rb"
[class]{}-[func]{quadratic_recur}
### 平方阶(递归实现)###
def quadratic_recur(n)
return 0 unless n > 0
# 数组 nums 长度为 n, n-1, ..., 2, 1
nums = Array.new(n, 0)
quadratic_recur(n - 1)
end
```
=== "Zig"
@@ -2199,7 +2240,15 @@ Exponential order is common in binary trees. Observe the below image, a "full bi
=== "Ruby"
```ruby title="space_complexity.rb"
[class]{}-[func]{build_tree}
### 指数阶(建立满二叉树)###
def build_tree(n)
return if n == 0
TreeNode.new.tap do |root|
root.left = build_tree(n - 1)
root.right = build_tree(n - 1)
end
end
```
=== "Zig"