From e99d23690e8fcb41ff92c807252b7499539a4390 Mon Sep 17 00:00:00 2001 From: xblakicex Date: Fri, 13 Jan 2023 20:41:18 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(space=5Fcomplexity):=20add=20r?= =?UTF-8?q?ust=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../space_complexity.rs | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 codes/rust/chapter_computational_complexity/space_complexity.rs diff --git a/codes/rust/chapter_computational_complexity/space_complexity.rs b/codes/rust/chapter_computational_complexity/space_complexity.rs new file mode 100644 index 000000000..a65ebb748 --- /dev/null +++ b/codes/rust/chapter_computational_complexity/space_complexity.rs @@ -0,0 +1,70 @@ +#![allow(unused_variables)] +/** + * File: space_complexity.cpp + * Created Time: 2023-01-13 + * Author: xBLACICEx (xBLACKICEx@outlook.com ) +*/ + +use std::collections::HashMap; + +/* 函数 */ +fn func() { + // do something +} + +/* 常数阶 */ +fn constant(n: i32) { + // TODO +} + +/* 线性阶 */ +fn linear(n: i32) { + // 长度为 n 的数组占用 O(n) 空间 + let nums = vec![0; n as usize]; + let map: HashMap<_, _> = (0..n).map(|i| (i, format!("{}", i))).collect(); +} + +/* 线性阶(递归实现) */ +fn linear_recur(n: i32) { + println!("递归 n = {n}"); + if n == 1 { + return; + } + linear_recur(n - 1); +} + +/* 平方阶 */ +fn quadratic(n: i32) { + // 二维列表占用 O(n^2) 空间 + let num_matrix = vec![vec![0; n as usize]; n as usize]; +} + +/* 平方阶(递归实现) */ +fn quadratic_recur(n: i32) -> i32 { + if n <= 0 { + return 0 + } + // 数组 nums 长度为 n, n-1, ..., 2, 1 + let nums = vec![0; n as usize]; + println!("递归 n = {n} 中的 nums 长度 = {}", nums.len()); + return quadratic_recur(n - 1); +} + +fn build_tree(n: usize) { + // TODO +} + +fn main() { + let n = 5; + /* 常数阶 */ + constant(n); + /* 线性阶 */ + linear(n); + linear_recur(n); + /* 平方阶 */ + quadratic(n); + quadratic_recur(n); + /* 指数阶 */ + // let root = build_tree(n); + // print_tree(root); +} \ No newline at end of file