You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/zh-hant/codes/swift/chapter_computational_compl.../space_complexity.swift

99 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* File: space_complexity.swift
* Created Time: 2023-01-01
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
@discardableResult
func function() -> Int {
//
return 0
}
/* */
func constant(n: Int) {
// O(1)
let a = 0
var b = 0
let nums = Array(repeating: 0, count: 10000)
let node = ListNode(x: 0)
// O(1)
for _ in 0 ..< n {
let c = 0
}
// O(1)
for _ in 0 ..< n {
function()
}
}
/* */
func linear(n: Int) {
// n O(n)
let nums = Array(repeating: 0, count: n)
// n O(n)
let nodes = (0 ..< n).map { ListNode(x: $0) }
// n O(n)
let map = Dictionary(uniqueKeysWithValues: (0 ..< n).map { ($0, "\($0)") })
}
/* */
func linearRecur(n: Int) {
print("遞迴 n = \(n)")
if n == 1 {
return
}
linearRecur(n: n - 1)
}
/* */
func quadratic(n: Int) {
// O(n^2)
let numList = Array(repeating: Array(repeating: 0, count: n), count: n)
}
/* */
@discardableResult
func quadraticRecur(n: Int) -> Int {
if n <= 0 {
return 0
}
// nums n, n-1, ..., 2, 1
let nums = Array(repeating: 0, count: n)
print("遞迴 n = \(n) 中的 nums 長度 = \(nums.count)")
return quadraticRecur(n: n - 1)
}
/* 滿 */
func buildTree(n: Int) -> TreeNode? {
if n == 0 {
return nil
}
let root = TreeNode(x: 0)
root.left = buildTree(n: n - 1)
root.right = buildTree(n: n - 1)
return root
}
@main
enum SpaceComplexity {
/* Driver Code */
static func main() {
let n = 5
//
constant(n: n)
//
linear(n: n)
linearRecur(n: n)
//
quadratic(n: n)
quadraticRecur(n: n)
//
let root = buildTree(n: n)
PrintUtil.printTree(root: root)
}
}