├── .gitignore ├── .test_repo ├── Cargo.lock ├── Cargo.toml └── src │ ├── 1629.lib.rs │ ├── 2022.lib.rs │ └── lib.rs ├── .vscode ├── launch.json └── settings.json ├── README.md ├── dynamic-programing ├── easy │ ├── NumArray │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── climb_stairs │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── divisor_game │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── fib │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── find_length_of_lcis │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── massage │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── max_profit │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── max_sub_array │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── min_cost_climbing_stairs │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── rob │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── sorted_squares │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ └── ways_to_step │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ ├── lib.rs │ │ └── main.rs └── medium │ ├── NumMatrix │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── can_jump │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── find_number_of_lis │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── jump │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── length_of_lis │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── longest_palindrome │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── maximal_square │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── min_path_sum │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── num_squares │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── number_of_arithmetic_slices │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── robs │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── robs3 │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ └── unique_paths_with_obstacles │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ └── lib.rs ├── hot100 ├── easy │ ├── add_strings │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ ├── binary_search │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ ├── find_disappeared_numbers │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── find_unsorted_subarray │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── first_bad_version │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ └── lemonade_change │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ ├── lib.rs │ │ └── main.rs ├── hard │ └── trap │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ └── lib.rs └── medium │ ├── can_finish │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── can_partition │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── change │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── coin_change │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── exist │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── generate_parenthesis │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── length_of_longest_substring │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── permute │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── product_except_self │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── search_range │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── sort_list │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── subsets │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── unique_paths │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ └── word_break │ ├── .gitignore │ ├── Cargo.toml │ └── src │ ├── lib.rs │ └── main.rs ├── images └── vscode.png ├── linkList ├── easy │ ├── delete_duplicates │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── delete_node │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── is_palindrome │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── middle_node │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ └── reverse_list │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ ├── lib.rs │ │ └── main.rs └── medium │ ├── add_two_numbers │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── delete_duplicates │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── merge_in_between │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── next_larger_nodes │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── remove_nth_from_end │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── remove_zero_sum_sublists │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── rotate_right │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ └── swap_pairs │ ├── .gitignore │ ├── Cargo.toml │ └── src │ ├── lib.rs │ └── main.rs ├── others ├── easy │ ├── MinStack │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ ├── MyQueue │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ ├── MyStack │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ ├── build_array │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ ├── construct2_d_array │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ ├── exchange │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ ├── find_judge │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ ├── generate │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ ├── is_subsequence │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ └── shortest_to_char │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ └── lib.rs ├── hard │ └── first_missing_positive │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ └── lib.rs └── medium │ ├── find_radius │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── increasing_triplet │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── k_smallest_pairs │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── last_remaining │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── max_area │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ └── max_increase_keeping_skyline │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ └── lib.rs ├── tree ├── easy │ ├── average_of_levels │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── binary_tree_paths │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── convert_bst │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── find_mode │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── find_tilt │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── is_balanced │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── is_same_tree │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── is_subtree │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── is_symmetric │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── kth_largest │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── leaf_similar │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── level_order_bottom │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── min_depth │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── min_diff_in_bst │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── range_sum_bst │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── search_bst │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ ├── sorted_array_to_bst │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── 322.lib.rs │ │ │ └── lib.rs │ ├── sum_of_left_leaves │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ │ ├── lib.rs │ │ │ └── main.rs │ └── trim_bst │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ ├── lib.rs │ │ └── main.rs ├── hard │ └── postorder_traversal │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ └── src │ │ ├── lib.rs │ │ └── main.rs └── medium │ ├── Trie │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── build_tree │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── build_tree_postorder │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── construct_from_pre_post │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── construct_maximum_binary_tree │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── count_nodes │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── flatten │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── inorder_traversal │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── is_valid_bst │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── level_order │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ ├── longest_univalue_path │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── lowest_common_ancestor │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── num_trees │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── lib.rs │ ├── preorder_traversal │ ├── .gitignore │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── main.rs │ └── zigzag_level_order │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ └── lib.rs └── weekly-test └── 2020-08-09 ├── can_convert_string ├── Cargo.lock ├── Cargo.toml └── src │ └── lib.rs └── find_kth_positive ├── Cargo.lock ├── Cargo.toml └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | .DS_Store -------------------------------------------------------------------------------- /.test_repo/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /.test_repo/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /.test_repo/src/1629.lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1629 lang=rust 3 | * 4 | * [1629] 按键持续时间最长的键 5 | */ 6 | 7 | // @lc code=start 8 | impl Solution { 9 | pub fn slowest_key(release_times: Vec, keys_pressed: String) -> char { 10 | 11 | } 12 | } 13 | // @lc code=end 14 | 15 | -------------------------------------------------------------------------------- /.test_repo/src/2022.lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=2022 lang=rust 3 | * 4 | * [2022] 将一维数组转变成二维数组 5 | */ 6 | 7 | // @lc code=start 8 | impl Solution { 9 | pub fn construct2_d_array(original: Vec, m: i32, n: i32) -> Vec> { 10 | 11 | } 12 | } 13 | // @lc code=end 14 | 15 | -------------------------------------------------------------------------------- /.test_repo/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=373 lang=rust 3 | * 4 | * [373] 查找和最小的K对数字 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | use std::cmp::Reverse; 9 | use std::collections::BinaryHeap; 10 | 11 | impl Solution { 12 | pub fn k_smallest_pairs(nums1: Vec, nums2: Vec, mut k: i32) -> Vec> { 13 | let mut res = vec![]; 14 | let mut heap = BinaryHeap::new(); 15 | for i in 0..nums1.len() { 16 | heap.push((Reverse(nums1[i] + nums2[0]), i, 0)) 17 | } 18 | while let Some((_, i, j)) = heap.pop() { 19 | if k <= 0 { 20 | break; 21 | } 22 | res.push(vec![nums1[i], nums2[j]]); 23 | if j + 1 < nums2.len() { 24 | heap.push((Reverse(nums1[i] + nums2[j + 1]), i, j + 1)); 25 | } 26 | k -= 1; 27 | } 28 | res 29 | } 30 | } 31 | // @lc code=end 32 | #[cfg(test)] 33 | mod tests { 34 | use super::*; 35 | 36 | #[test] 37 | fn tests() { 38 | Solution::k_smallest_pairs(vec![1, 1, 2], vec![1, 2, 3], 8); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "lldb", 9 | "request": "launch", 10 | "name": "Debug", 11 | "args": [], 12 | "cwd": "${workspaceFolder}", 13 | "cargo": { 14 | "args": [ 15 | "test", 16 | "--no-run", 17 | "--lib", 18 | "--manifest-path=.test_repo/Cargo.toml" 19 | ], 20 | "filter": { 21 | "name": "leetcodebyrust", 22 | "kind": "lib" 23 | } 24 | }, 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "[rust]": { // Tells VSCode to defer to rust-analyzer's formatter (rustfmt) for rust code 3 | "editor.defaultFormatter": "matklad.rust-analyzer" // 4 | }, 5 | "editor.formatOnSave": true 6 | } -------------------------------------------------------------------------------- /dynamic-programing/easy/NumArray/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/easy/NumArray/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/easy/NumArray/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=303 lang=rust 3 | * 4 | * [303] 区域和检索 - 数组不可变 5 | */ 6 | 7 | // @lc code=start 8 | struct NumArray { 9 | nums: Vec, 10 | subscript: Vec, // 代表 以 i 为 右侧索引的范围和 11 | } 12 | 13 | /** 14 | * `&self` means the method takes an immutable reference. 15 | * If you need a mutable reference, change it to `&mut self` instead. 16 | */ 17 | impl NumArray { 18 | // fn new(nums: Vec) -> Self { 19 | // NumArray { 20 | // subscript: vec![0; nums.len()], 21 | // nums, 22 | // } 23 | // } 24 | 25 | // fn sum_range(&mut self, i: i32, j: i32) -> i32 { 26 | // let start = i as usize; 27 | // let end = j as usize; 28 | // if start != 0 && self.subscript[start - 1] == 0 { 29 | // let mut sum = 0; 30 | // for i in 0..=start - 1 { 31 | // sum += self.nums[i] 32 | // } 33 | // self.subscript[start - 1] = sum 34 | // } 35 | // if self.subscript[end] == 0 { 36 | // let mut sum = 0; 37 | // for i in 0..=end { 38 | // sum += self.nums[i] 39 | // } 40 | // self.subscript[end] = sum 41 | // } 42 | // if start == 0 { 43 | // self.subscript[end] 44 | // } else { 45 | // self.subscript[end] - self.subscript[start - 1] 46 | // } 47 | // } 48 | fn new(nums: Vec) -> Self { 49 | let mut subscript = vec![0; nums.len()]; 50 | let mut sum = 0; 51 | for i in 0..nums.len() { 52 | sum += nums[i]; 53 | subscript[i] = sum; 54 | } 55 | NumArray { subscript, nums } 56 | } 57 | 58 | fn sum_range(&mut self, i: i32, j: i32) -> i32 { 59 | if i == 0 { 60 | self.subscript[j as usize] 61 | } else { 62 | self.subscript[j as usize] - self.subscript[i as usize - 1] 63 | } 64 | } 65 | } 66 | 67 | // /** 68 | // * Your NumArray object will be instantiated and called as such: 69 | // * let obj = NumArray::new(nums); 70 | // * let ret_1: i32 = obj.sum_range(i, j); 71 | // */ 72 | // @lc code=end 73 | -------------------------------------------------------------------------------- /dynamic-programing/easy/NumArray/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /dynamic-programing/easy/climb_stairs/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/easy/climb_stairs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/easy/climb_stairs/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | 3 | impl Solution { 4 | pub fn climb_stairs(n: i32) -> i32 { 5 | let nsize = n as usize; 6 | let mut v: Vec = vec![1, 2]; 7 | let mut i: usize = 2; 8 | while i < nsize { 9 | v.push(v.get(i - 1).unwrap() + v.get(i - 2).unwrap()); 10 | i += 1; 11 | } 12 | *v.get(nsize - 1).unwrap() // 这里要返回i32而不是&i32所以使用解引用 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /dynamic-programing/easy/climb_stairs/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /dynamic-programing/easy/divisor_game/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/easy/divisor_game/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rob" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/easy/divisor_game/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution {} 2 | 3 | // 爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。 4 | 5 | // 最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作: 6 | 7 | // 选出任一 x,满足 0 < x < N 且 N % x == 0 。 8 | // 用 N - x 替换黑板上的数字 N 。 9 | // 如果玩家无法执行这些操作,就会输掉游戏。 10 | 11 | // 只有在爱丽丝在游戏中取得胜利时才返回 True,否则返回 false。假设两个玩家都以最佳状态参与游戏。 12 | 13 | impl Solution { 14 | pub fn divisor_game(n: i32) -> bool { 15 | // 如果第x步爱丽丝赢了,则代表x+1不能满足条件 16 | // x-1满足条件 17 | let dp: Vec = vec![]; 18 | if dp[i] {} 19 | true 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /dynamic-programing/easy/divisor_game/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /dynamic-programing/easy/fib/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/easy/fib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/easy/fib/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=509 lang=rust 3 | * 4 | * [509] 斐波那契数 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | impl Solution { 9 | pub fn fib(n: i32) -> i32 { 10 | let n = n as usize; 11 | let mut dp = vec![0, 1, 1]; 12 | if n <= 2 { 13 | return dp[n]; 14 | } 15 | 16 | for i in 2..=n { 17 | dp[0] = dp[1]; 18 | dp[1] = dp[2]; 19 | dp[2] = dp[0] + dp[1]; 20 | } 21 | dp[1] 22 | } 23 | } 24 | // @lc code=end 25 | #[cfg(test)] 26 | mod tests { 27 | use super::*; 28 | 29 | #[test] 30 | fn tests() { 31 | println!("{:?}", Solution::fib(6)) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /dynamic-programing/easy/fib/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /dynamic-programing/easy/find_length_of_lcis/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/easy/find_length_of_lcis/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/easy/find_length_of_lcis/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | use std::cmp::max; 3 | 4 | // 输入: [1,3,5,4,7] 5 | // 输出: 3 6 | // 解释: 最长连续递增序列是 [1,3,5], 长度为3。 7 | // 尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。 8 | 9 | impl Solution { 10 | pub fn find_length_of_lcis(nums: Vec) -> i32 { 11 | if nums.len() <= 1 { 12 | return nums.len() as i32; 13 | } 14 | let mut res = 1; 15 | let mut path = vec![1; nums.len()]; 16 | for i in 1..nums.len() { 17 | if nums[i] > nums[i - 1] { 18 | path[i] = path[i - 1] + 1; 19 | res = max(res, path[i]); 20 | } 21 | } 22 | res 23 | } 24 | } 25 | 26 | #[cfg(test)] 27 | mod tests { 28 | use super::*; 29 | 30 | #[test] 31 | fn tests() { 32 | Solution::find_length_of_lcis(vec![1, 3, 5, 4, 7]); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /dynamic-programing/easy/find_length_of_lcis/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /dynamic-programing/easy/massage/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/easy/massage/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "massage" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/easy/massage/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution {} 2 | 3 | use std::cmp::max; 4 | 5 | pub fn massage(nums: Vec) -> i32 { 6 | if nums.len() == 0 { 7 | return 0; 8 | } 9 | let mut res = nums[0]; 10 | let len = nums.len(); 11 | let mut dp: Vec> = vec![vec![0, nums[0]]; len]; // 设定length定义dp二维数组 12 | for i in 1..len { 13 | if dp.get(i).is_none() { 14 | dp[i] = vec![0, 0] 15 | } 16 | 17 | dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]); // dp[i][0] 表示前i个预约第i个预约不接的最长时间 18 | dp[i][1] = dp[i - 1][0] + nums[i]; // dp[i][1] 表示前i个预约第i个预约接的最长时间 19 | res = max(max(res, dp[i][0]), dp[i][1]) 20 | } 21 | res 22 | } 23 | 24 | #[cfg(test)] 25 | mod tests { 26 | use super::*; 27 | 28 | #[test] 29 | fn tests() { 30 | let nums: Vec = vec![2, 1, 4, 5, 3, 1, 1, 3]; 31 | massage(nums); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /dynamic-programing/easy/massage/src/main.rs: -------------------------------------------------------------------------------- 1 | use massage::massage; 2 | 3 | fn main() { 4 | let nums: Vec = vec![1, 2, 3, 1]; 5 | massage(nums); 6 | } 7 | -------------------------------------------------------------------------------- /dynamic-programing/easy/max_profit/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/easy/max_profit/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/easy/max_profit/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=121 lang=rust 3 | * 4 | * [121] 买卖股票的最佳时机 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | use std::cmp::max; 9 | use std::cmp::min; 10 | 11 | impl Solution { 12 | pub fn max_profit(prices: Vec) -> i32 { 13 | if prices.len() == 0 || prices.len() == 1 { 14 | return 0; 15 | } 16 | let mut min_sign = prices[0]; // 记录当天之前的最低价格 17 | let mut dp = vec![0; prices.len()]; // dp 代表当天卖出能获得的最大收益 18 | let mut res = 0; 19 | dp[0] = 0; 20 | for i in 1..prices.len() { 21 | dp[i] = prices[i] - min_sign; 22 | min_sign = min(min_sign, prices[i]); 23 | res = max(res, dp[i]) 24 | } 25 | res 26 | } 27 | } 28 | // @lc code=end 29 | 30 | #[cfg(test)] 31 | mod tests { 32 | use super::*; 33 | 34 | #[test] 35 | fn tests() { 36 | println!("{:?}", Solution::max_profit(vec![1])) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /dynamic-programing/easy/max_profit/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /dynamic-programing/easy/max_sub_array/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/easy/max_sub_array/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/easy/max_sub_array/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution {} 2 | 3 | use std::cmp::max; 4 | 5 | impl Solution { 6 | pub fn max_sub_array(nums: Vec) -> i32 { 7 | let mut res = nums[0]; 8 | let mut sum = 0; 9 | for num in nums { 10 | if sum <= 0 { 11 | sum = num; 12 | } else { 13 | // 如果当前的sum大于0就一直加下去。如果小于0就从当前值重新开始 14 | sum += num; 15 | } 16 | res = max(res, sum); 17 | } 18 | res 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /dynamic-programing/easy/max_sub_array/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /dynamic-programing/easy/min_cost_climbing_stairs/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/easy/min_cost_climbing_stairs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rob" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/easy/min_cost_climbing_stairs/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution {} 2 | use std::cmp::min; 3 | 4 | impl Solution { 5 | pub fn min_cost_climbing_stairs(mut cost: Vec) -> i32 { 6 | cost.push(0); // 爬楼梯的最后一步当成是无消耗的,需要额外增加一个0元素 7 | let mut dp = vec![cost[0]; cost.len()]; 8 | dp[1] = cost[1]; // 跳到第一个和第二个阶梯的答案就是cost对应的位置本身 9 | for i in 2..cost.len() { 10 | dp[i] = min(dp[i - 1] + cost[i], dp[i - 2] + cost[i]); // 第i层有两种可能分别是从前1个跳过来,或者前2个调过来 11 | } 12 | dp.pop().unwrap() 13 | } 14 | } 15 | 16 | #[cfg(test)] 17 | mod tests { 18 | use super::*; 19 | 20 | #[test] 21 | fn tests() { 22 | let cost: Vec = vec![1, 100, 1, 1, 1, 100, 1, 1, 100, 1]; 23 | Solution::min_cost_climbing_stairs(cost); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /dynamic-programing/easy/min_cost_climbing_stairs/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /dynamic-programing/easy/rob/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/easy/rob/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rob" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/easy/rob/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution {} 2 | 3 | use std::cmp::max; 4 | 5 | // 跟按摩师一模一样的题目 6 | pub fn rob(nums: Vec) -> i32 { 7 | if nums.len() == 0 { 8 | return 0; 9 | } 10 | let mut res = nums[0]; 11 | let len = nums.len(); 12 | let mut dp: Vec> = vec![vec![0, nums[0]]; len]; // 设定length定义dp二维数组 13 | for i in 1..len { 14 | if dp.get(i).is_none() { 15 | dp[i] = vec![0, 0] 16 | } 17 | 18 | dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]); // dp[i][0] 表示前i个预约第i个预约不接的最长时间 19 | dp[i][1] = dp[i - 1][0] + nums[i]; // dp[i][1] 表示前i个预约第i个预约接的最长时间 20 | res = max(max(res, dp[i][0]), dp[i][1]) 21 | } 22 | res 23 | } 24 | 25 | #[cfg(test)] 26 | mod tests { 27 | use super::*; 28 | 29 | #[test] 30 | fn tests() { 31 | let nums: Vec = vec![2, 1, 4, 5, 3, 1, 1, 3]; 32 | rob(nums); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /dynamic-programing/easy/rob/src/main.rs: -------------------------------------------------------------------------------- 1 | use rob::rob; 2 | 3 | fn main() { 4 | let nums: Vec = vec![1, 2, 3, 1]; 5 | rob(nums); 6 | } 7 | -------------------------------------------------------------------------------- /dynamic-programing/easy/sorted_squares/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/easy/sorted_squares/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/easy/sorted_squares/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=977 lang=rust 3 | * 4 | * [977] 有序数组的平方 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | 9 | impl Solution { 10 | pub fn sorted_squares(mut nums: Vec) -> Vec { 11 | let mut dp = vec![]; 12 | let mut start = 0; 13 | let mut end = nums.len() - 1; 14 | while start <= end { 15 | let mut val; 16 | if nums[start].abs() >= nums[end].abs() { 17 | val = nums[start]; 18 | start += 1; 19 | } else { 20 | val = nums[end]; 21 | end -= 1; 22 | }; 23 | dp.push(val * val) 24 | } 25 | dp.reverse(); 26 | dp 27 | } 28 | } 29 | // @lc code=end 30 | #[cfg(test)] 31 | mod tests { 32 | use super::*; 33 | 34 | #[test] 35 | fn tests() { 36 | println!("{:?}", Solution::sorted_squares(vec![1])) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /dynamic-programing/easy/sorted_squares/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /dynamic-programing/easy/ways_to_step/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/easy/ways_to_step/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/easy/ways_to_step/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution {} 2 | use std::cmp::max; 3 | 4 | impl Solution { 5 | pub fn ways_to_step(n: i32) -> i32 { 6 | let len = max(n, 3); 7 | let mut dp = vec![0; len as usize]; 8 | dp[0] = 1; 9 | dp[1] = 2; 10 | dp[2] = 4; 11 | let mut i: usize = 3; 12 | while i < n as usize { 13 | for j in 1..4 { 14 | dp[i] += (dp[i - j]) % 1000000007; 15 | dp[i] = dp[i] % 1000000007; 16 | } 17 | i += 1; 18 | } 19 | let res: i32 = dp[(n - 1) as usize]; 20 | res 21 | } 22 | } 23 | 24 | #[cfg(test)] 25 | mod tests { 26 | use super::*; 27 | 28 | #[test] 29 | fn tests() { 30 | Solution::ways_to_step(61); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /dynamic-programing/easy/ways_to_step/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /dynamic-programing/medium/NumMatrix/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /dynamic-programing/medium/NumMatrix/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/medium/NumMatrix/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=304 lang=rust 3 | * 4 | * [304] 二维区域和检索 - 矩阵不可变 5 | */ 6 | 7 | // @lc code=start 8 | struct NumMatrix { 9 | matrix: Vec>, 10 | subscriptSum: Vec>, 11 | } 12 | 13 | /** 14 | * `&self` means the method takes an immutable reference. 15 | * If you need a mutable reference, change it to `&mut self` instead. 16 | */ 17 | impl NumMatrix { 18 | fn new(matrix: Vec>) -> Self { 19 | if matrix.len() == 0 { 20 | return NumMatrix { 21 | matrix, 22 | subscriptSum: vec![vec![]], 23 | }; 24 | } 25 | let mut subscriptSum = vec![vec![0; matrix[0].len()]; matrix.len()]; 26 | // 思路: 类似 https://leetcode-cn.com/problems/range-sum-query-immutable/ 27 | // 分别计算每一行以每个元素为结束位置的和, 换成二维矩阵后把每一行的计算结果相加即可 28 | for i in 0..matrix.len() { 29 | let mut sum = 0; 30 | for j in 0..matrix[0].len() { 31 | sum += matrix[i][j]; 32 | subscriptSum[i][j] = sum 33 | } 34 | sum = 0; 35 | } 36 | NumMatrix { 37 | matrix, 38 | subscriptSum, 39 | } 40 | } 41 | 42 | fn sum_region(&self, row1: i32, col1: i32, row2: i32, col2: i32) -> i32 { 43 | let cols = (col2 - col1) as usize; 44 | let rows = (row2 - row1) as usize; 45 | let mut sum = 0; 46 | let mut row = row1 as usize; 47 | let col = col1 as usize; 48 | for i in 0..=rows { 49 | if col == 0 { 50 | sum += self.subscriptSum[row][col + cols] 51 | } else { 52 | sum += self.subscriptSum[row][col + cols] - self.subscriptSum[(row)][col - 1]; 53 | } 54 | 55 | row += 1; 56 | } 57 | sum 58 | } 59 | } 60 | 61 | // /** 62 | // * Your NumMatrix object will be instantiated and called as such: 63 | // * let obj = NumMatrix::new(matrix); 64 | // * let ret_1: i32 = obj.sum_region(row1, col1, row2, col2); 65 | // */ 66 | // @lc code=end 67 | -------------------------------------------------------------------------------- /dynamic-programing/medium/can_jump/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /dynamic-programing/medium/can_jump/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/medium/can_jump/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=55 lang=rust 3 | * 4 | * [55] 跳跃游戏 5 | */ 6 | struct Solution {} 7 | 8 | // @lc code=start 9 | impl Solution { 10 | pub fn can_jump(nums: Vec) -> bool { 11 | let n = nums.len(); 12 | let mut dp = vec![false; n]; 13 | dp[0] = true; 14 | for i in 1..nums.len() { 15 | for j in 0..i { 16 | dp[i] = if dp[j] && nums[j] >= (i - j) as i32 { 17 | true 18 | } else { 19 | false 20 | }; 21 | if dp[i] { 22 | break; 23 | } 24 | } 25 | } 26 | return dp[n - 1]; 27 | } 28 | } 29 | // @lc code=end 30 | 31 | #[cfg(test)] 32 | 33 | mod tests { 34 | use super::*; 35 | #[test] 36 | fn name() { 37 | println!("{:?}", Solution::can_jump(vec![2, 3, 1, 1, 4])); 38 | println!("{:?}", Solution::can_jump(vec![3, 2, 1, 0, 4])) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /dynamic-programing/medium/find_number_of_lis/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/medium/find_number_of_lis/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/medium/find_number_of_lis/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /dynamic-programing/medium/jump/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /dynamic-programing/medium/jump/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/medium/jump/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=45 lang=rust 3 | * 4 | * [45] 跳跃游戏 II 5 | */ 6 | 7 | struct Solution {} 8 | // @lc code=start 9 | impl Solution { 10 | pub fn jump(nums: Vec) -> i32 { 11 | let n = nums.len(); 12 | let mut dp = vec![i32::MAX; n]; // 跳到 i 的最小步数 13 | dp[0] = 0; 14 | for i in 1..nums.len() { 15 | for j in 0..i { 16 | if nums[j] >= (i - j) as i32 { 17 | // dp[i] = true; 18 | dp[i] = dp[i].min(dp[j] + 1); 19 | } 20 | } 21 | } 22 | dp[n - 1] 23 | } 24 | } 25 | // @lc code=end 26 | #[cfg(test)] 27 | mod tests { 28 | use super::*; 29 | 30 | #[test] 31 | fn tests() { 32 | println!("{:?}", Solution::jump(vec![1, 2, 3, 4])); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /dynamic-programing/medium/length_of_lis/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /dynamic-programing/medium/length_of_lis/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/medium/length_of_lis/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | use std::cmp::max; 3 | 4 | // 只要 nums[i] 严格大于在它位置之前的某个数,那么 nums[i] 就可以接在这个数后面形成一个更长的上升子序列; 5 | // 因此,dp[i] 就等于下标 i 之前严格小于 nums[i] 的状态值的最大者 +1。 6 | // 语言描述:在下标 i 之前严格小于 nums[i] 的所有状态值中的最大者 +1。 7 | 8 | // 符号描述: 9 | 10 | // dp[i] = \max_{0 \le j < i, nums[j] < nums[i]} {dp[j] + 1} 11 | // dp[i]= 12 | // 0≤j) -> i32 { 18 | if nums.len() <= 1 { 19 | return nums.len() as i32; 20 | } 21 | let mut dp = vec![1; nums.len()]; 22 | // dp[i]代表到i为止最长的递增子序列长度 23 | for i in 1..nums.len() { 24 | for j in 0..i { 25 | if nums[i] > nums[j] { 26 | dp[i] = max(dp[j] + 1, dp[i]); 27 | } 28 | } 29 | } 30 | let mut res = dp[0]; 31 | for i in dp { 32 | res = max(res, i); 33 | } 34 | res 35 | } 36 | } 37 | 38 | #[cfg(test)] 39 | mod tests { 40 | use super::*; 41 | 42 | #[test] 43 | fn tests() { 44 | Solution::length_of_lis(vec![1, 3, 6, 7, 9, 4, 10, 5, 6]); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /dynamic-programing/medium/length_of_lis/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /dynamic-programing/medium/longest_palindrome/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /dynamic-programing/medium/longest_palindrome/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/medium/maximal_square/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /dynamic-programing/medium/maximal_square/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/medium/maximal_square/src/lib.rs: -------------------------------------------------------------------------------- 1 | // 一维数组 2 | /* 3 | * @lc app=leetcode.cn id=413 lang=rust 4 | * 5 | * [413] 等差数列划分 6 | */ 7 | struct Solution {} 8 | // @lc code=start 9 | impl Solution { 10 | pub fn number_of_arithmetic_slices(nums: Vec) -> i32 { 11 | let n = nums.len(); 12 | let mut dp = vec![false; n]; 13 | let mut res = 0; 14 | dp[0] = true; 15 | for i in 0..n { 16 | for j in (i + 1)..n { 17 | if j - i <= 1 { 18 | dp[j] = true; 19 | continue; 20 | } 21 | dp[j] = if dp[j - 1] && nums[j] - nums[j - 1] == nums[j - 1] - nums[j - 2] { 22 | true 23 | } else { 24 | false 25 | }; 26 | if dp[j] && j >= 2 { 27 | res = res + 1; 28 | } 29 | } 30 | } 31 | res 32 | } 33 | } 34 | // @lc code=end 35 | 36 | // @lc code=end 37 | #[cfg(test)] 38 | mod tests { 39 | use super::*; 40 | 41 | #[test] 42 | fn tests() { 43 | println!( 44 | "{:?}", 45 | Solution::number_of_arithmetic_slices(vec![1, 2, 3, 4]) 46 | ); 47 | println!("{:?}", Solution::number_of_arithmetic_slices(vec![1])) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /dynamic-programing/medium/min_path_sum/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /dynamic-programing/medium/min_path_sum/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/medium/min_path_sum/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=64 lang=rust 3 | * 4 | * [64] 最小路径和 5 | */ 6 | 7 | struct Solution {} 8 | // @lc code=start 9 | use std::cmp::min; 10 | 11 | impl Solution { 12 | pub fn min_path_sum(grid: Vec>) -> i32 { 13 | let m = grid.len(); 14 | let n = grid[0].len(); 15 | let mut dp = vec![vec![1; grid[0].len()]; m]; // dp代表到m*n坐标时候的最小路径和 16 | dp[0][0] = grid[0][0]; 17 | for i in 1..m { 18 | dp[i][0] = grid[i][0] + dp[i - 1][0] 19 | } 20 | for j in 1..n { 21 | dp[0][j] = grid[0][j] + dp[0][j - 1] 22 | } 23 | for i in 1..m { 24 | for j in 1..n { 25 | dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j] 26 | } 27 | } 28 | println!("{:?}", dp); 29 | dp[m - 1][n - 1] 30 | } 31 | } 32 | // @lc code=end 33 | #[cfg(test)] 34 | mod tests { 35 | use super::*; 36 | 37 | #[test] 38 | fn tests() { 39 | Solution::min_path_sum(vec![vec![1, 2, 5], vec![3, 2, 1]]); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /dynamic-programing/medium/num_squares/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /dynamic-programing/medium/num_squares/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/medium/num_squares/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=279 lang=rust 3 | * 4 | * [279] 完全平方数 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | use std::cmp::min; 9 | impl Solution { 10 | pub fn num_squares(n: i32) -> i32 { 11 | let nusize = n as usize; 12 | let mut dp = vec![0; nusize + 1]; 13 | for i in 1..=nusize { 14 | dp[i] = i; 15 | let mut j = 1; 16 | while i >= j * j { 17 | // 找到相差一个完全平方数的最小结果+1 18 | dp[i] = min(dp[i], dp[i - j * j] + 1); 19 | j += 1; 20 | } 21 | } 22 | dp[nusize] as i32 23 | } 24 | } 25 | // @lc code=end 26 | -------------------------------------------------------------------------------- /dynamic-programing/medium/number_of_arithmetic_slices/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /dynamic-programing/medium/number_of_arithmetic_slices/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/medium/number_of_arithmetic_slices/src/lib.rs: -------------------------------------------------------------------------------- 1 | // 一维数组 2 | /* 3 | * @lc app=leetcode.cn id=413 lang=rust 4 | * 5 | * [413] 等差数列划分 6 | */ 7 | struct Solution {} 8 | // @lc code=start 9 | impl Solution { 10 | pub fn number_of_arithmetic_slices(nums: Vec) -> i32 { 11 | let n = nums.len(); 12 | let mut dp = vec![false; n]; 13 | let mut res = 0; 14 | dp[0] = true; 15 | for i in 0..n { 16 | for j in (i + 1)..n { 17 | if j - i <= 1 { 18 | dp[j] = true; 19 | continue; 20 | } 21 | dp[j] = if dp[j - 1] && nums[j] - nums[j - 1] == nums[j - 1] - nums[j - 2] { 22 | true 23 | } else { 24 | false 25 | }; 26 | if dp[j] && j >= 2 { 27 | res = res + 1; 28 | } 29 | } 30 | } 31 | res 32 | } 33 | } 34 | // @lc code=end 35 | 36 | // @lc code=end 37 | #[cfg(test)] 38 | mod tests { 39 | use super::*; 40 | 41 | #[test] 42 | fn tests() { 43 | println!( 44 | "{:?}", 45 | Solution::number_of_arithmetic_slices(vec![1, 2, 3, 4]) 46 | ); 47 | println!("{:?}", Solution::number_of_arithmetic_slices(vec![1])) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /dynamic-programing/medium/robs/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /dynamic-programing/medium/robs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/medium/robs/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=213 lang=rust 3 | * 4 | * [213] 打家劫舍 II 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | use std::cmp::max; 9 | impl Solution { 10 | pub fn rob(nums: Vec) -> i32 { 11 | if nums.len() == 0 { 12 | return 0; 13 | } 14 | if nums.len() == 1 { 15 | return nums[0]; 16 | } 17 | // 思路: 只需单独处理第一个和最后一个房屋,中间的房屋仍然和打家劫舍1一样处理 18 | return max( 19 | Self::rob1(nums[0..=nums.len() - 2].to_vec()), // 抢第一个,则不能抢最后一个 20 | Self::rob1(nums[1..=nums.len() - 1].to_vec()), // 不抢第一个,则可以抢最后一个 21 | ); 22 | } 23 | fn rob1(nums: Vec) -> i32 { 24 | // 处理中间的房子,相当于直线排列的房子 25 | if nums.len() == 1 { 26 | return nums[0]; 27 | } 28 | // dp 定义为最后一个房间可获得的最大金额 29 | let mut dp = vec![0; nums.len()]; 30 | dp[0] = nums[0]; 31 | dp[1] = max(nums[0], nums[1]); 32 | for i in 2..nums.len() { 33 | dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]) 34 | } 35 | return dp[nums.len() - 1]; 36 | } 37 | } 38 | // @lc code=end 39 | 40 | #[cfg(test)] 41 | mod tests { 42 | use super::*; 43 | 44 | #[test] 45 | fn tests() { 46 | println!("{:?}", Solution::rob(vec![1, 2])) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /dynamic-programing/medium/robs3/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /dynamic-programing/medium/robs3/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/medium/robs3/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=337 lang=rust 3 | * 4 | * [337] 打家劫舍 III 5 | */ 6 | struct Solution {} 7 | #[derive(Debug, PartialEq, Eq)] 8 | pub struct TreeNode { 9 | pub val: i32, 10 | pub left: Option>>, 11 | pub right: Option>>, 12 | } 13 | 14 | impl TreeNode { 15 | #[inline] 16 | pub fn new(val: i32) -> Self { 17 | TreeNode { 18 | val, 19 | left: None, 20 | right: None, 21 | } 22 | } 23 | } 24 | // @lc code=start 25 | // Definition for a binary tree node. 26 | // #[derive(Debug, PartialEq, Eq)] 27 | // pub struct TreeNode { 28 | // pub val: i32, 29 | // pub left: Option>>, 30 | // pub right: Option>>, 31 | // } 32 | // 33 | // impl TreeNode { 34 | // #[inline] 35 | // pub fn new(val: i32) -> Self { 36 | // TreeNode { 37 | // val, 38 | // left: None, 39 | // right: None 40 | // } 41 | // } 42 | // } 43 | use std::cell::RefCell; 44 | use std::cmp::max; 45 | use std::rc::Rc; 46 | impl Solution { 47 | pub fn rob(root: Option>>) -> i32 { 48 | let (robed, noRobed) = check(root); 49 | return max(robed, noRobed); 50 | } 51 | } 52 | fn check(root: Option>>) -> (i32, i32) { 53 | if root.is_none() { 54 | return (0, 0); 55 | } 56 | let l = check(root.as_ref().unwrap().borrow_mut().left.take()); 57 | let r = check(root.as_ref().unwrap().borrow_mut().right.take()); 58 | 59 | let robed = root.as_ref().unwrap().borrow().val + l.1 + r.1; 60 | let noRobed = max(l.1, l.0) + max(r.0, r.1); 61 | (robed, noRobed) 62 | } 63 | // @lc code=end 64 | -------------------------------------------------------------------------------- /dynamic-programing/medium/unique_paths_with_obstacles/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /dynamic-programing/medium/unique_paths_with_obstacles/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /dynamic-programing/medium/unique_paths_with_obstacles/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=63 lang=rust 3 | * 4 | * [63] 不同路径 II 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | impl Solution { 9 | pub fn unique_paths_with_obstacles(obstacle_grid: Vec>) -> i32 { 10 | let m = obstacle_grid.len(); 11 | let n = obstacle_grid[0].len(); 12 | let mut dp = vec![vec![1; n]; m]; 13 | // 特殊处理第一列的情况 14 | let mut hasObstacle = false; 15 | for i in 0..n { 16 | if obstacle_grid[0][i] == 1 { 17 | hasObstacle = true 18 | } 19 | if hasObstacle { 20 | dp[0][i] = 0 21 | } 22 | } 23 | hasObstacle = false; 24 | // 特殊处理第一行的情况 25 | for i in 0..m { 26 | if obstacle_grid[i][0] == 1 { 27 | hasObstacle = true 28 | } 29 | if hasObstacle { 30 | dp[i][0] = 0 31 | } 32 | } 33 | for i in 1..m { 34 | for j in 1..n { 35 | let top = if obstacle_grid[i - 1][j] == 1 { 36 | 0 37 | } else { 38 | dp[i - 1][j] 39 | }; 40 | let left = if obstacle_grid[i][j - 1] == 1 { 41 | 0 42 | } else { 43 | dp[i][j - 1] 44 | }; 45 | dp[i][j] = top + left; 46 | if obstacle_grid[i][j] == 1 { 47 | dp[i][j] = 0 48 | } 49 | } 50 | } 51 | dp[m - 1][n - 1] 52 | } 53 | } 54 | // @lc code=end 55 | -------------------------------------------------------------------------------- /hot100/easy/add_strings/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /hot100/easy/add_strings/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/easy/binary_search/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /hot100/easy/binary_search/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/easy/binary_search/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=704 lang=rust 3 | * 4 | * [704] 二分查找 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | impl Solution { 9 | pub fn search(nums: Vec, target: i32) -> i32 { 10 | if nums.len() == 1 { 11 | if nums[0] == target { 12 | return 0; 13 | } else { 14 | return -1; 15 | } 16 | } 17 | let left = 0; 18 | let right = nums.len() - 1; 19 | return Self::binary_search(nums, target, left, right); 20 | } 21 | fn binary_search(nums: Vec, target: i32, left: usize, right: usize) -> i32 { 22 | if right < left { 23 | return -1; 24 | } 25 | let pivot_index = (right + left) / 2; 26 | if nums[pivot_index] == target { 27 | return pivot_index as i32; 28 | } 29 | if nums[pivot_index] < target { 30 | return Self::binary_search(nums, target, pivot_index + 1, right); 31 | } else { 32 | if pivot_index == 0 { 33 | // 防止 usize 溢出 34 | return -1; 35 | } 36 | return Self::binary_search(nums, target, left, pivot_index - 1); 37 | } 38 | } 39 | } 40 | // @lc code=end 41 | 42 | #[cfg(test)] 43 | mod tests { 44 | use super::*; 45 | 46 | #[test] 47 | fn tests() { 48 | let nums: Vec = vec![2, 5]; 49 | println!("{:?}", Solution::search(nums, 0)); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /hot100/easy/find_disappeared_numbers/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/easy/find_disappeared_numbers/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/easy/find_disappeared_numbers/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | 3 | impl Solution { 4 | pub fn find_disappeared_numbers(mut nums: Vec) -> Vec { 5 | // O(n)的解法一般都需要用到原地标记 6 | let mut i = 0; 7 | let mut res = vec![]; 8 | while i < nums.len() { 9 | let key = (nums[i].abs() - 1) as usize; 10 | if nums[key] > 0 { 11 | nums[key] = nums[key] * -1; 12 | } 13 | i += 1; 14 | } 15 | let mut i = 0; 16 | while i < nums.len() { 17 | if nums[i] > 0 { 18 | res.push((i + 1) as i32); 19 | } 20 | i += 1; 21 | } 22 | println!("{:?}", res); 23 | res 24 | } 25 | } 26 | #[cfg(test)] 27 | mod tests { 28 | use super::*; 29 | 30 | #[test] 31 | fn tests() { 32 | Solution::find_disappeared_numbers(vec![4, 3, 2, 7, 8, 2, 3, 1]); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /hot100/easy/find_disappeared_numbers/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /hot100/easy/find_unsorted_subarray/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/easy/find_unsorted_subarray/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/easy/find_unsorted_subarray/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | 3 | impl Solution { 4 | pub fn find_unsorted_subarray(nums: Vec) -> i32 { 5 | // 时间复杂度O(n) 6 | if nums.len() == 1 { 7 | return 0; 8 | } 9 | let mut c_max = nums[0]; // 记录当前选取的数组范围内的最大值 10 | let mut c_min = nums[0]; // 记录当前选取的数组范围内的最小值 11 | let mut start = 0; 12 | let mut end = 0; 13 | let mut sign = false; 14 | for i in 0..nums.len() { 15 | if sign == false && i + 1 < nums.len() && nums[i + 1] < nums[i] { 16 | start = i; // 6 记录数组开始的下标 17 | c_max = nums[i]; // 6 18 | c_min = nums[i + 1]; 19 | end = i + 1; // 4 记录数组结束时的下标 20 | sign = true; // 只需要首次找到的结果即可 21 | } 22 | if nums[i] > c_max { 23 | c_max = nums[i]; 24 | } 25 | if nums[i] < c_min { 26 | c_min = nums[i]; 27 | } 28 | if nums[i] < c_max { 29 | // 如果当前值比之前选取的数组中的最大值小,则说明当前值应该被包含进去 30 | end = i; 31 | } 32 | } 33 | if end == start && end == 0 { 34 | return 0; 35 | } 36 | 37 | for i in (0..start).rev() { 38 | if nums[i] > c_min { 39 | // 如果start前面的数字小于当前数组中的最小值,则start往前移动 40 | start -= 1; 41 | } else { 42 | break; 43 | } 44 | } 45 | 46 | println!("{:?}", format!("{}{}", end, start)); 47 | 48 | (end - start + 1) as i32 49 | } 50 | } 51 | #[cfg(test)] 52 | mod tests { 53 | use super::*; 54 | 55 | #[test] 56 | fn tests() { 57 | Solution::find_unsorted_subarray(vec![2, 6, 4, 8, 10, 9, 15]); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /hot100/easy/find_unsorted_subarray/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /hot100/easy/first_bad_version/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /hot100/easy/first_bad_version/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/easy/first_bad_version/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=278 lang=rust 3 | * 4 | * [278] 第一个错误的版本 5 | */ 6 | struct Solution {} 7 | impl Solution { 8 | fn isBadVersion(&self, n: i32) -> bool { 9 | if n == 1702766719 { 10 | return true; 11 | } else { 12 | return false; 13 | } 14 | } 15 | } 16 | // @lc code=start 17 | // The API isBadVersion is defined for you. 18 | // isBadVersion(versions:i32)-> bool; 19 | // to call it use self.isBadVersion(versions) 20 | 21 | impl Solution { 22 | // 找左边界 23 | pub fn first_bad_version(&self, n: i32) -> i32 { 24 | return Self::search(&self, n); 25 | } 26 | fn search(&self, n: i32) -> i32 { 27 | if n == 1 && self.isBadVersion(1) { 28 | return 1; 29 | } 30 | let left = 0; 31 | let right = n as i64; 32 | return Self::binary_search(&self, n, left, right); 33 | } 34 | fn binary_search(&self, n: i32, left: i64, right: i64) -> i32 { 35 | if right < left { 36 | println!("{:?} {}", left, right); 37 | return left as i32; 38 | } 39 | let pivot = (right + left) / 2; 40 | if self.isBadVersion(pivot as i32) { 41 | // 如果找到了,则调整右边界 42 | return Self::binary_search(&self, n, left, pivot - 1); 43 | } else { 44 | // 没找到则调整左边界 45 | return Self::binary_search(&self, n, pivot + 1, right); 46 | } 47 | } 48 | } 49 | // @lc code=end 50 | #[cfg(test)] 51 | mod tests { 52 | use super::*; 53 | 54 | #[test] 55 | fn tests() { 56 | let so = Solution {}; 57 | println!("{:?}", so.first_bad_version(2126753390)); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /hot100/easy/lemonade_change/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/easy/lemonade_change/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/easy/lemonade_change/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /hot100/hard/trap/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /hot100/hard/trap/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/hard/trap/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=42 lang=rust 3 | * 4 | * [42] 接雨水 5 | */ 6 | 7 | struct Solution {} 8 | // @lc code=start 9 | use std::cmp::min; 10 | 11 | impl Solution { 12 | pub fn trap(height: Vec) -> i32 { 13 | if height.len() == 0 { 14 | return 0; 15 | } 16 | if height.len() == 1 { 17 | return 0; 18 | } 19 | let mut left_max = vec![0; height.len()]; // 记录左边的最大高度 20 | let mut right_max = vec![0; height.len()]; // 记录右边的最大高度 21 | let mut temp_left_max = 0; 22 | let mut temp_right_max = 0; 23 | for i in 0..height.len() { 24 | left_max[i] = temp_left_max; 25 | if height[i] > temp_left_max { 26 | temp_left_max = height[i] 27 | } 28 | } 29 | for i in (0..height.len()).rev() { 30 | right_max[i] = temp_right_max; 31 | if height[i] > temp_right_max { 32 | temp_right_max = height[i] 33 | } 34 | } 35 | println!("{:?}", left_max); 36 | println!("{:?}", right_max); 37 | let mut res = 0; 38 | for i in 1..height.len() - 1 { 39 | // 当前能够接住的雨水高度为左边的最大高度减去右边的最大高度的绝对值再减去当前的高度 40 | let min_height = min(right_max[i], left_max[i]); 41 | if min_height - height[i] > 0 { 42 | res += min_height - height[i]; 43 | } 44 | } 45 | println!("{:?}", res); 46 | 47 | res 48 | } 49 | } 50 | // @lc code=end 51 | 52 | #[cfg(test)] 53 | mod tests { 54 | use super::*; 55 | 56 | #[test] 57 | fn tests() { 58 | let nums: Vec = vec![0, 2, 0]; 59 | Solution::trap(nums); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /hot100/medium/can_finish/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /hot100/medium/can_finish/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/can_finish/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=207 lang=rust 3 | * 4 | * [207] 课程表 5 | */ 6 | 7 | struct Solution {} 8 | // @lc code=start 9 | use std::collections::HashMap; 10 | 11 | impl Solution { 12 | pub fn can_finish(num_courses: i32, prerequisites: Vec>) -> bool { 13 | let mut hash_map: HashMap> = HashMap::new(); 14 | for i in prerequisites { 15 | if hash_map.get(&i[0]).is_none() { 16 | hash_map.insert(i[0], vec![i[1]]); 17 | } else { 18 | let val = hash_map.get_mut(&i[0]).unwrap(); 19 | val.push(i[1]); 20 | } 21 | } 22 | let mut res = true; 23 | let hash_map_clone = hash_map.clone(); 24 | for (key, val) in hash_map.iter_mut() { 25 | *val = add_path(&mut vec![*key], val.clone(), &hash_map_clone); 26 | } 27 | for (key, val) in hash_map.iter() { 28 | if val.contains(key) { 29 | res = false; 30 | break; 31 | } 32 | } 33 | res 34 | } 35 | } 36 | 37 | fn add_path(key: &mut Vec, val_vec: Vec, hash_map: &HashMap>) -> Vec { 38 | let mut foo = val_vec.clone(); 39 | for val in val_vec { 40 | match hash_map.get(&val) { 41 | Some(next_val) => { 42 | if check_key_repect(&foo, key) { 43 | break; 44 | } 45 | key.push(val); 46 | foo.extend(add_path(key, next_val.to_owned(), hash_map)); 47 | } 48 | None => {} 49 | } 50 | } 51 | foo 52 | } 53 | fn check_key_repect(foo: &Vec, key: &mut Vec) -> bool { 54 | for i in key { 55 | if foo.contains(&i) { 56 | return true; 57 | } 58 | } 59 | return false; 60 | } 61 | // @lc code=end 62 | #[cfg(test)] 63 | mod tests { 64 | use super::*; 65 | 66 | #[test] 67 | fn tests() { 68 | Solution::can_finish(3, vec![vec![0, 2], vec![1, 2], vec![2, 0]]); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /hot100/medium/can_partition/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/medium/can_partition/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/can_partition/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | use std::cmp::max; 3 | 4 | impl Solution { 5 | // 01背包变种 6 | pub fn can_partition(nums: Vec) -> bool { 7 | // 由于两个集合相等,即每一个集合的sum为总和/2 8 | let sum = get_sum(&nums); 9 | if sum % 2 != 0 { 10 | // 和为奇数直接跳出 11 | return false; 12 | } 13 | let sum_half = sum / 2; 14 | zero_one_pack(&nums, sum_half) 15 | } 16 | } 17 | 18 | fn get_sum(nums: &Vec) -> usize { 19 | let mut sum = 0; 20 | for i in nums { 21 | sum += i; 22 | } 23 | sum as usize 24 | } 25 | fn zero_one_pack(nums: &Vec, sum: usize) -> bool { 26 | // 01背包,物品个数为nums.len,背包容量为sum 27 | let mut dp = vec![0; sum + 1]; 28 | let mut res = false; 29 | for i in 1..nums.len() + 1 { 30 | let weight = nums[i - 1]; 31 | let val = nums[i - 1]; 32 | for j in (1..sum + 1).rev() { 33 | if j >= weight as usize { 34 | dp[j] = max(dp[j], dp[j - weight as usize] + val as usize); 35 | } 36 | } 37 | } 38 | println!("{:?}", dp); 39 | println!("{:?}", sum); 40 | if dp.pop().unwrap() == sum { 41 | true 42 | } else { 43 | false 44 | } 45 | } 46 | 47 | #[cfg(test)] 48 | mod tests { 49 | use super::*; 50 | 51 | #[test] 52 | fn tests() { 53 | let coins: Vec = vec![1, 2, 3, 6]; 54 | Solution::can_partition(coins); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /hot100/medium/can_partition/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /hot100/medium/change/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/medium/change/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/change/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | use std::cmp::max; 3 | 4 | impl Solution { 5 | // 完全背包问题的变种 6 | pub fn coin_change(amount: i32, coins: Vec) -> i32 { 7 | let amount = amount as usize; 8 | let mut dp = vec![0; amount + 1]; 9 | dp[0] = 0; 10 | for i in 1..coins.len() + 1 { 11 | let weight = coins[i - 1]; 12 | let val = coins[i - 1] as usize; 13 | for j in val..amount + 1 { 14 | dp[j] = max(dp[j], dp[j - weight as usize]); 15 | } 16 | } 17 | println!("{:?}", dp); 18 | 1 19 | } 20 | } 21 | 22 | #[cfg(test)] 23 | mod tests { 24 | use super::*; 25 | 26 | #[test] 27 | fn tests() { 28 | let coins: Vec = vec![1, 2, 5]; 29 | Solution::coin_change(5, coins); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /hot100/medium/change/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /hot100/medium/coin_change/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/medium/coin_change/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/coin_change/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | use std::cmp::min; 3 | 4 | impl Solution { 5 | // 完全背包问题的变种 6 | pub fn coin_change(coins: Vec, amount: i32) -> i32 { 7 | // 本题可以看liweiwei的分析,写的特别清晰 https://leetcode-cn.com/problems/coin-change/solution/dong-tai-gui-hua-shi-yong-wan-quan-bei-bao-wen-ti-/ 8 | // dp[amout]的含义为凑成amount金额所需要的最小硬币数量 9 | let amount = amount as usize; 10 | let mut dp = vec![amount + 1; amount + 1]; 11 | dp[0] = 0; 12 | for i in 1..amount + 1 { 13 | for j in 0..coins.len() { 14 | if coins[j] as usize <= i { 15 | dp[i] = min(dp[i], dp[i - coins[j] as usize] + 1); 16 | } 17 | } 18 | } 19 | 20 | if dp[amount] == amount + 1 { 21 | -1 22 | } else { 23 | dp[amount] as i32 24 | } 25 | } 26 | } 27 | 28 | #[cfg(test)] 29 | mod tests { 30 | use super::*; 31 | 32 | #[test] 33 | fn tests() { 34 | let coins: Vec = vec![1, 2, 6]; 35 | Solution::coin_change(coins, 11); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /hot100/medium/coin_change/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /hot100/medium/exist/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/medium/exist/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/exist/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /hot100/medium/generate_parenthesis/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/medium/generate_parenthesis/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/generate_parenthesis/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | 3 | impl Solution { 4 | pub fn generate_parenthesis(n: i32) -> Vec { 5 | let mut res: Vec = vec![]; // 存放结果 6 | let mut path = String::from(""); // 存放当前路径, 第一个路径是固定的 7 | back_trace(&mut res, &mut path, 0, 0, n); 8 | println!("{:?}", res); 9 | res 10 | } 11 | } 12 | 13 | fn back_trace(res: &mut Vec, path: &mut String, left: i32, right: i32, n: i32) { 14 | if path.len() == 2 * n as usize { 15 | // 递归结束 16 | res.push(path.clone()); 17 | return; 18 | } 19 | if left < n { 20 | let mut path = path.clone(); 21 | path.push_str("("); 22 | back_trace(res, &mut path, left + 1, right, n) 23 | } 24 | if left > 0 && left > right && right < n { 25 | // 剪枝(左括号可以使用的个数严格大于右括号可以使用的个数,才剪枝 26 | let mut path = path.clone(); 27 | path.push_str(")"); 28 | back_trace(res, &mut path, left, right + 1, n) 29 | } 30 | } 31 | 32 | #[cfg(test)] 33 | mod tests { 34 | use super::*; 35 | 36 | #[test] 37 | fn tests() { 38 | Solution::generate_parenthesis(3); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /hot100/medium/generate_parenthesis/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /hot100/medium/length_of_longest_substring/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /hot100/medium/length_of_longest_substring/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/length_of_longest_substring/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=3 lang=rust 3 | * 4 | * [3] 无重复字符的最长子串 5 | */ 6 | pub struct Solution {} 7 | 8 | // @lc code=start 9 | use std::cmp::max; 10 | impl Solution { 11 | pub fn length_of_longest_substring(s: String) -> i32 { 12 | // 使用滑动窗口 13 | if s == "" { 14 | return 0; 15 | } 16 | let mut start = 0; 17 | let mut end = 1; 18 | let mut res = 1; // 获取当前窗口长度 19 | while end != s.len() { 20 | // println!("{} {}", &s[start..end], &s[end..end + 1]); 21 | if !&s[start..end].contains(&s[end..end + 1]) { 22 | end += 1; // 窗口向右扩大 23 | res = max(res, s[start..end].len()) 24 | } else { 25 | // 窗口从左边缩小 26 | start += 1; 27 | if start >= end { 28 | end = start + 1; 29 | } 30 | } 31 | } 32 | println!("{}", res); 33 | res as i32 34 | } 35 | } 36 | // @lc code=end 37 | #[cfg(test)] 38 | mod tests { 39 | use super::*; 40 | 41 | #[test] 42 | fn tests() { 43 | assert_eq!( 44 | Solution::length_of_longest_substring("pwwkew".to_string()), 45 | 3 46 | ); 47 | assert_eq!(Solution::length_of_longest_substring("aaa".to_string()), 1); 48 | 49 | assert_eq!(Solution::length_of_longest_substring("dvdf".to_string()), 3); 50 | assert_eq!( 51 | Solution::length_of_longest_substring("anviaj".to_string()), 52 | 5 53 | ); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /hot100/medium/permute/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/medium/permute/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/permute/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | 3 | impl Solution { 4 | pub fn permute(nums: Vec) -> Vec> { 5 | let mut res: Vec> = vec![]; // 记录最终结果 6 | let mut path: Vec = vec![]; // 记录当前的path 7 | back_trace(&mut res, &mut path, &nums); 8 | res 9 | } 10 | } 11 | 12 | fn back_trace(res: &mut Vec>, path: &mut Vec, nums: &Vec) { 13 | if path.len() == nums.len() { 14 | res.push(path.clone()); // 所有的数字都使用了,递归结束 15 | return; 16 | } 17 | for i in 0..nums.len() { 18 | if path.contains(&nums[i]) { 19 | // 说明当前的path vector已经有该数字了,跳出该循环 20 | continue; 21 | } 22 | path.push(nums[i]); // 选择数字 23 | back_trace(res, path, nums); 24 | path.pop(); // 撤销选择 25 | } 26 | } 27 | 28 | #[cfg(test)] 29 | mod tests { 30 | use super::*; 31 | 32 | #[test] 33 | fn tests() { 34 | Solution::permute(vec![1, 2, 3]); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /hot100/medium/permute/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /hot100/medium/product_except_self/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/medium/product_except_self/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/product_except_self/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | 3 | // 60(2) = 3*4*5 4 | // 40(3) = 2*4*5 5 | // 30(4) = 2 * 3 * 5 6 | // 24(5) = 2*3*4 7 | impl Solution { 8 | pub fn product_except_self(nums: Vec) -> Vec { 9 | let mut dp = vec![0; nums.len()]; 10 | dp[0] = 1; 11 | for i in 1..nums.len() { 12 | // 左侧数字的乘积 13 | dp[i] = nums[i - 1] * dp[i - 1] 14 | } 15 | let mut j = nums.len() - 1; 16 | let mut R = 1; 17 | while j >= 0 { 18 | // 乘以右侧数字的乘积 19 | dp[j] = dp[j] * R; 20 | R *= nums[j]; 21 | if j == 0 { 22 | // 这里break方式防止usize为负数导致panic 23 | break; 24 | } 25 | j -= 1; 26 | } 27 | dp 28 | } 29 | } 30 | 31 | #[cfg(test)] 32 | mod tests { 33 | use super::*; 34 | 35 | #[test] 36 | fn tests() { 37 | let nums: Vec = vec![1, 2, 3, 4]; 38 | Solution::product_except_self(nums); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /hot100/medium/product_except_self/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /hot100/medium/search_range/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /hot100/medium/search_range/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/sort_list/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/medium/sort_list/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/sort_list/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | // Definition for singly-linked list. 3 | // #[derive(PartialEq, Eq, Clone, Debug)] 4 | pub struct ListNode { 5 | pub val: i32, 6 | pub next: Option>, 7 | } 8 | 9 | impl ListNode { 10 | #[inline] 11 | fn new(val: i32) -> Self { 12 | ListNode { next: None, val } 13 | } 14 | } 15 | impl Solution { 16 | pub fn sort_list(head: Option>) -> Option> { 17 | head 18 | } 19 | } 20 | 21 | fn sort(left: Option>, right: Option>) {} 22 | -------------------------------------------------------------------------------- /hot100/medium/sort_list/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /hot100/medium/subsets/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/medium/subsets/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/subsets/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | 3 | impl Solution { 4 | pub fn subsets(mut nums: Vec) -> Vec> { 5 | // 本质上类似于子集的全排列 6 | let mut res: Vec> = vec![]; 7 | Self::get_subsets(&nums, &mut res, &mut vec![], 0); 8 | println!("{:?}", res); 9 | res 10 | } 11 | fn get_subsets(nums: &Vec, res: &mut Vec>, path: &mut Vec, start: usize) { 12 | res.push(path.clone()); 13 | for i in start..nums.len() { 14 | path.push(nums[i]); 15 | let start = i + 1; 16 | Self::get_subsets(nums, res, path, start); 17 | path.pop(); 18 | } 19 | } 20 | } 21 | 22 | #[cfg(test)] 23 | mod tests { 24 | use super::*; 25 | 26 | #[test] 27 | fn tests() { 28 | Solution::subsets(vec![1, 2, 3]); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /hot100/medium/subsets/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /hot100/medium/unique_paths/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/medium/unique_paths/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/unique_paths/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=62 lang=rust 3 | * 4 | * [62] 不同路径 5 | */ 6 | 7 | struct Solution {} 8 | // @lc code=start 9 | 10 | impl Solution { 11 | pub fn unique_paths(m: i32, n: i32) -> i32 { 12 | // let m = m as usize; 13 | // let n = n as usize; 14 | // let mut dp = vec![vec![1; n]; m]; // dp[i][j]的含义为i*j的网格有多少条路径 15 | // for i in 1..m { 16 | // for j in 1..n { 17 | // dp[i][j] = dp[i - 1][j] + dp[i][j - 1] 18 | // } 19 | // } 20 | // dp[m - 1][n - 1] 21 | // 2压缩数组后 22 | let m = m as usize; 23 | let n = n as usize; 24 | let mut dp = vec![1; n]; // dp[j]的含义为i*j的网格有多少条路径 25 | for i in 1..m { 26 | for j in 1..n { 27 | dp[j] = dp[j] + dp[j - 1] 28 | } 29 | } 30 | dp[n - 1] 31 | } 32 | } 33 | 34 | #[cfg(test)] 35 | mod tests { 36 | use super::*; 37 | 38 | #[test] 39 | fn tests() { 40 | println!("{:?}", Solution::unique_paths(3, 2)) 41 | } 42 | } 43 | 44 | // @lc code=end 45 | -------------------------------------------------------------------------------- /hot100/medium/unique_paths/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /hot100/medium/word_break/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /hot100/medium/word_break/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /hot100/medium/word_break/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | 3 | impl Solution { 4 | pub fn word_break(mut s: String, mut word_dict: Vec) -> bool { 5 | // 参考题解 https://leetcode-cn.com/problems/word-break/solution/dan-ci-chai-fen-ju-jue-zhuang-xcong-jian-dan-de-xi/ 6 | // 动态规划算法,dp[i]表示s前i个字符能否拆分 7 | // 转移方程:dp[j] = dp[i] && check(s[i+1, j]); 8 | let mut dp = vec![true; s.len() + 1]; 9 | for i in 1..s.len() + 1 { 10 | for j in (0..i).rev() { 11 | dp[i] = dp[j] && word_dict.contains(&s[j..i].to_string()); 12 | if dp[i] { 13 | break; 14 | } 15 | } 16 | } 17 | println!("{:?}", dp); 18 | dp[dp.len() - 1] 19 | } 20 | } 21 | 22 | #[cfg(test)] 23 | mod tests { 24 | use super::*; 25 | 26 | #[test] 27 | fn tests() { 28 | Solution::word_break( 29 | "leetcode".to_string(), 30 | vec!["leet".to_string(), "code".to_string()], 31 | ); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /hot100/medium/word_break/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /images/vscode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangyuang/leetcode/f965a4dd47cb615b351a7be672cad7e0abb8ebd6/images/vscode.png -------------------------------------------------------------------------------- /linkList/easy/delete_duplicates/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /linkList/easy/delete_duplicates/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /linkList/easy/delete_duplicates/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=83 lang=rust 3 | * 4 | * [83] 删除排序链表中的重复元素 5 | */ 6 | struct Solution {} 7 | // Definition for singly-linked list. 8 | #[derive(PartialEq, Eq, Clone, Debug)] 9 | pub struct ListNode { 10 | pub val: i32, 11 | pub next: Option>, 12 | } 13 | 14 | impl ListNode { 15 | #[inline] 16 | fn new(val: i32) -> Self { 17 | ListNode { next: None, val } 18 | } 19 | } 20 | // @lc code=start 21 | // Definition for singly-linked list. 22 | // #[derive(PartialEq, Eq, Clone, Debug)] 23 | // pub struct ListNode { 24 | // pub val: i32, 25 | // pub next: Option> 26 | // } 27 | // 28 | // impl ListNode { 29 | // #[inline] 30 | // fn new(val: i32) -> Self { 31 | // ListNode { 32 | // next: None, 33 | // val 34 | // } 35 | // } 36 | // } 37 | impl Solution { 38 | pub fn delete_duplicates(mut head: Option>) -> Option> { 39 | if head.is_none() || head.as_ref()?.next.is_none() { 40 | return head; 41 | } 42 | let mut root = &mut head; 43 | 44 | while root.is_some() && root.as_mut()?.next.is_some() { 45 | let mut node = root.as_mut().unwrap(); 46 | let next_node = &mut node.next; 47 | if next_node.as_ref()?.val == node.val { 48 | node.next = next_node.as_mut()?.next.take(); 49 | } else { 50 | root = &mut root.as_mut()?.next; 51 | } 52 | } 53 | head 54 | } 55 | } 56 | // @lc code=end 57 | -------------------------------------------------------------------------------- /linkList/easy/delete_duplicates/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /linkList/easy/delete_node/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /linkList/easy/delete_node/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /linkList/easy/delete_node/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Definition for singly-linked list. 2 | #[derive(PartialEq, Eq, Clone, Debug)] 3 | pub struct ListNode { 4 | pub val: i32, 5 | pub next: Option>, 6 | } 7 | 8 | impl ListNode { 9 | #[inline] 10 | fn new(val: i32) -> Self { 11 | ListNode { next: None, val } 12 | } 13 | } 14 | 15 | struct Solution {} 16 | 17 | fn delete_node(head: Option>, val: i32) -> Option> { 18 | let mut head = Some(Box::new(ListNode { val: 1, next: head })); 19 | let mut root = &mut head; 20 | while let Some(node) = root { 21 | let next_node = &mut node.next; 22 | match next_node { 23 | None => break, 24 | Some(next_node) => { 25 | if next_node.val == val { 26 | // 当前节点的下一个节点等于目标节点 27 | node.next = next_node.next.take(); 28 | break; 29 | } 30 | } 31 | } 32 | root = &mut node.next; 33 | } 34 | head.unwrap().next 35 | } 36 | -------------------------------------------------------------------------------- /linkList/easy/delete_node/src/main.rs: -------------------------------------------------------------------------------- 1 | #[derive(PartialEq, Eq, Clone, Debug)] 2 | pub struct ListNode { 3 | pub val: i32, 4 | pub next: Option>, 5 | } 6 | 7 | impl ListNode { 8 | #[inline] 9 | fn new(val: i32) -> Self { 10 | ListNode { next: None, val } 11 | } 12 | } 13 | fn main() { 14 | let mut head = Some(Box::new(ListNode { next: None, val: 0 })); 15 | 16 | print!("{:?}", head.unwrap().next); 17 | } 18 | -------------------------------------------------------------------------------- /linkList/easy/is_palindrome/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /linkList/easy/is_palindrome/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /linkList/easy/is_palindrome/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Definition for singly-linked list. 2 | #[derive(PartialEq, Eq, Clone, Debug)] 3 | pub struct ListNode { 4 | pub val: i32, 5 | pub next: Option>, 6 | } 7 | 8 | impl ListNode { 9 | #[inline] 10 | fn new(val: i32) -> Self { 11 | ListNode { next: None, val } 12 | } 13 | } 14 | 15 | struct Solution {} 16 | 17 | impl Solution { 18 | pub fn is_palindrome(head: Option>) -> bool { 19 | if head.is_none() { 20 | return true; 21 | } 22 | let mut vec = Vec::new(); 23 | let mut root = &head; 24 | 25 | while let Some(node) = root { 26 | vec.push(node); 27 | root = &node.next; 28 | } 29 | let mut root = &head; 30 | while let Some(node) = root { 31 | let mut top = vec.pop().unwrap(); 32 | if top.val != node.val { 33 | return false; 34 | } 35 | root = &node.next; 36 | } 37 | true 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /linkList/easy/is_palindrome/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /linkList/easy/middle_node/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /linkList/easy/middle_node/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /linkList/easy/middle_node/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Definition for singly-linked list. 2 | #[derive(PartialEq, Eq, Clone, Debug)] 3 | pub struct ListNode { 4 | pub val: i32, 5 | pub next: Option>, 6 | } 7 | 8 | impl ListNode { 9 | #[inline] 10 | fn new(val: i32) -> Self { 11 | ListNode { next: None, val } 12 | } 13 | } 14 | 15 | struct Solution {} 16 | 17 | fn middle_node(mut head: Option>) -> Option> { 18 | let mut len: f64 = 0.0; 19 | let mut root = &mut head; 20 | while root.is_some() { 21 | len += 1.0; 22 | root = &mut root.as_mut().unwrap().next; 23 | } 24 | let middle_index = (len / 2.0).floor(); 25 | let mut i = 0.0; 26 | root = &mut head; 27 | while i < middle_index { 28 | i += 1.0; 29 | root = &mut root.as_mut().unwrap().next; 30 | } 31 | root.take() 32 | } 33 | -------------------------------------------------------------------------------- /linkList/easy/middle_node/src/main.rs: -------------------------------------------------------------------------------- 1 | #[derive(PartialEq, Eq, Clone, Debug)] 2 | pub struct ListNode { 3 | pub val: i32, 4 | pub next: Option>, 5 | } 6 | 7 | impl ListNode { 8 | #[inline] 9 | fn new(val: i32) -> Self { 10 | ListNode { next: None, val } 11 | } 12 | } 13 | fn main() { 14 | let mut head = Some(Box::new(ListNode { next: None, val: 0 })); 15 | 16 | print!("{:?}", head.unwrap().next); 17 | } 18 | -------------------------------------------------------------------------------- /linkList/easy/reverse_list/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /linkList/easy/reverse_list/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /linkList/easy/reverse_list/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Definition for singly-linked list. 2 | #[derive(PartialEq, Eq, Clone, Debug)] 3 | pub struct ListNode { 4 | pub val: i32, 5 | pub next: Option>, 6 | } 7 | 8 | impl ListNode { 9 | #[inline] 10 | fn new(val: i32) -> Self { 11 | ListNode { next: None, val } 12 | } 13 | } 14 | 15 | struct Solution {} 16 | 17 | fn reverse_list(head: Option>) -> Option> { 18 | if head.is_none() { 19 | return None; 20 | } 21 | let mut prev: Option> = None; 22 | let mut curr: Option> = head; 23 | while curr.is_some() { 24 | let mut node = curr.take().unwrap(); 25 | curr = node.next; 26 | node.next = prev; 27 | prev = Some(node); 28 | } 29 | prev 30 | } 31 | -------------------------------------------------------------------------------- /linkList/easy/reverse_list/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut foo = Box::new(1); 3 | let mut bar = &mut foo; 4 | println!("{:?}", **bar); 5 | } 6 | -------------------------------------------------------------------------------- /linkList/medium/add_two_numbers/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /linkList/medium/add_two_numbers/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /linkList/medium/add_two_numbers/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Definition for singly-linked list. 2 | #[derive(PartialEq, Eq, Clone, Debug)] 3 | pub struct ListNode { 4 | pub val: i32, 5 | pub next: Option>, 6 | } 7 | 8 | impl ListNode { 9 | #[inline] 10 | fn new(val: i32) -> Self { 11 | ListNode { next: None, val } 12 | } 13 | } 14 | 15 | struct Solution {} 16 | 17 | // Rust没有原生的bigint类型,所以在测试用例的极端场景会溢出。leetcode不支持引入第三方crate。所以最佳解决方案应该是按位相加然后进位。或者使用其他提供Bigint类型的语言如js,java 18 | // 由于主要目的是熟悉Rust语法,这里就直接使用两数相加的解法来写了, 底部附上使用js的解法 19 | fn add_two_numbers( 20 | mut l1: Option>, 21 | mut l2: Option>, 22 | ) -> Option> { 23 | let l1_sum = get_sum(&mut l1); 24 | let l2_sum = get_sum(&mut l2); 25 | let mut sum = l1_sum + l2_sum; 26 | let mut head = Some(Box::new(ListNode::new(0))); 27 | let mut root = &mut head; 28 | if sum == 0 { 29 | return head; 30 | } 31 | while (sum != 0) { 32 | let node = Some(Box::new(ListNode::new(sum.wrapping_rem(10) as i32))); 33 | root.as_mut().unwrap().next = node; 34 | root = &mut root.as_mut().unwrap().next; 35 | sum = sum.wrapping_div_euclid(10); 36 | } 37 | head.unwrap().next 38 | } 39 | 40 | fn get_sum(head: &mut Option>) -> i128 { 41 | let mut root = head; 42 | let mut sum: i128 = 0; 43 | let mut bit: i128 = 1; 44 | while let Some(node) = root { 45 | sum += node.val as i128 * bit; 46 | bit *= 10; 47 | root = &mut node.next; 48 | } 49 | sum 50 | } 51 | 52 | // fix addTwoNumbers by js use Bigint 53 | // var addTwoNumbers = function (l1, l2) { 54 | // let sum = getSum(l1) + getSum(l2) 55 | // let res = new ListNode(0) 56 | // if (sum === 0n) { 57 | // return res 58 | // } 59 | // let foo = res 60 | // while (sum != 0) { 61 | // const node = new ListNode(sum % 10n) 62 | // res.next = node 63 | // res = res.next 64 | // sum = sum / 10n 65 | // } 66 | // return foo.next 67 | // }; 68 | 69 | // const getSum = list => { 70 | // let sum = 0n; 71 | // let bit = 1n; 72 | // while (list) { 73 | // sum += BigInt(list.val) * bit 74 | // bit *= 10n 75 | // list = list.next 76 | // } 77 | // return sum 78 | // } 79 | -------------------------------------------------------------------------------- /linkList/medium/add_two_numbers/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /linkList/medium/delete_duplicates/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /linkList/medium/delete_duplicates/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /linkList/medium/delete_duplicates/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=82 lang=rust 3 | * 4 | * [82] 删除排序链表中的重复元素 II 5 | */ 6 | struct Solution {} 7 | #[derive(PartialEq, Eq, Clone, Debug)] 8 | pub struct ListNode { 9 | pub val: i32, 10 | pub next: Option>, 11 | } 12 | 13 | impl ListNode { 14 | #[inline] 15 | fn new(val: i32) -> Self { 16 | ListNode { next: None, val } 17 | } 18 | } 19 | // @lc code=start 20 | // Definition for singly-linked list. 21 | // #[derive(PartialEq, Eq, Clone, Debug)] 22 | // pub struct ListNode { 23 | // pub val: i32, 24 | // pub next: Option> 25 | // } 26 | // 27 | // impl ListNode { 28 | // #[inline] 29 | // fn new(val: i32) -> Self { 30 | // ListNode { 31 | // next: None, 32 | // val 33 | // } 34 | // } 35 | // } 36 | impl Solution { 37 | pub fn delete_duplicates(head: Option>) -> Option> { 38 | let mut phead = Some(Box::new(ListNode { 39 | val: -1, 40 | next: head, 41 | })); 42 | let mut root = &mut phead; 43 | while root.is_some() && root.as_mut()?.next.is_some() { 44 | let root_next = &mut root.as_mut()?.next; 45 | let root_next_ref = root_next.as_mut()?; 46 | let root_next_next = &mut root_next_ref.next; 47 | if root_next_next.is_some() { 48 | if root_next_ref.val == root_next_next.as_ref()?.val { 49 | let res = root_next_ref.val; 50 | let mut guard = root_next_next; 51 | while guard.is_some() { 52 | // 找到第一个值不等于重复值的节点 53 | if guard.as_ref()?.val != res { 54 | break; 55 | } 56 | guard = &mut guard.as_mut()?.next; 57 | } 58 | if guard.is_some() { 59 | root.as_mut()?.next = guard.take(); 60 | continue; 61 | } else { 62 | root.as_mut()?.next = None; 63 | } 64 | } 65 | } 66 | root = &mut root.as_mut()?.next; 67 | } 68 | phead.as_mut()?.next.take() 69 | } 70 | } 71 | // @lc code=end 72 | -------------------------------------------------------------------------------- /linkList/medium/delete_duplicates/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /linkList/medium/merge_in_between/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /linkList/medium/merge_in_between/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /linkList/medium/merge_in_between/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1669 lang=rust 3 | * 4 | * [1669] 合并两个链表 5 | */ 6 | //Definition for singly-linked list. 7 | #[derive(PartialEq, Eq, Clone, Debug)] 8 | pub struct ListNode { 9 | pub val: i32, 10 | pub next: Option>, 11 | } 12 | 13 | impl ListNode { 14 | #[inline] 15 | fn new(val: i32) -> Self { 16 | ListNode { next: None, val } 17 | } 18 | } 19 | struct Solution {} 20 | // @lc code=start 21 | // Definition for singly-linked list. 22 | // #[derive(PartialEq, Eq, Clone, Debug)] 23 | // pub struct ListNode { 24 | // pub val: i32, 25 | // pub next: Option> 26 | // } 27 | // 28 | // impl ListNode { 29 | // #[inline] 30 | // fn new(val: i32) -> Self { 31 | // ListNode { 32 | // next: None, 33 | // val 34 | // } 35 | // } 36 | // } 37 | impl Solution { 38 | pub fn merge_in_between( 39 | mut list1: Option>, 40 | a: i32, 41 | b: i32, 42 | list2: Option>, 43 | ) -> Option> { 44 | let mut head_clone = list1.clone(); 45 | let mut head = &mut list1; 46 | let mut left = 1; 47 | let mut right = 1; 48 | while right != b + 2 { 49 | head_clone = head_clone?.next; 50 | right += 1; 51 | } 52 | while left != a { 53 | head = &mut head.as_mut()?.next; 54 | left += 1; 55 | } 56 | head.as_mut()?.next = list2; 57 | while head.as_mut()?.next.is_some() { 58 | head = &mut head.as_mut()?.next; 59 | } 60 | head.as_mut()?.next = head_clone; 61 | list1 62 | } 63 | } 64 | // @lc code=end 65 | -------------------------------------------------------------------------------- /linkList/medium/merge_in_between/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /linkList/medium/next_larger_nodes/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /linkList/medium/next_larger_nodes/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /linkList/medium/next_larger_nodes/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /linkList/medium/remove_nth_from_end/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /linkList/medium/remove_nth_from_end/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /linkList/medium/remove_nth_from_end/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=19 lang=rust 3 | * 4 | * [19] 删除链表的倒数第N个节点 5 | */ 6 | // Definition for singly-linked list. 7 | #[derive(PartialEq, Eq, Clone, Debug)] 8 | pub struct ListNode { 9 | pub val: i32, 10 | pub next: Option>, 11 | } 12 | 13 | impl ListNode { 14 | #[inline] 15 | fn new(val: i32) -> Self { 16 | ListNode { next: None, val } 17 | } 18 | } 19 | struct Solution {} 20 | // @lc code=start 21 | // Definition for singly-linked list. 22 | // #[derive(PartialEq, Eq, Clone, Debug)] 23 | // pub struct ListNode { 24 | // pub val: i32, 25 | // pub next: Option> 26 | // } 27 | // 28 | // impl ListNode { 29 | // #[inline] 30 | // fn new(val: i32) -> Self { 31 | // ListNode { 32 | // next: None, 33 | // val 34 | // } 35 | // } 36 | // } 37 | impl Solution { 38 | pub fn remove_nth_from_end(mut head: Option>, n: i32) -> Option> { 39 | if head.is_none() { 40 | return head; 41 | } 42 | let mut slow = &head; 43 | let mut fast = &head; 44 | let mut i = 1; 45 | while i < n { 46 | // 快指针先走n步 47 | fast = &fast.as_ref()?.next; 48 | i += 1; 49 | } 50 | while fast.as_ref()?.next.is_some() { 51 | fast = &fast.as_ref()?.next; 52 | slow = &slow.as_ref()?.next; 53 | } 54 | // 这里必须clone一下因为head已经borrow了,没办法再move 55 | head = delete_node(head.clone(), slow); 56 | head 57 | } 58 | } 59 | 60 | fn delete_node( 61 | head: Option>, 62 | target: &Option>, 63 | ) -> Option> { 64 | let mut phead = Some(Box::new(ListNode { val: 1, next: head })); 65 | let mut root = &mut phead; 66 | while root.as_mut()?.next.is_some() { 67 | if &root.as_mut()?.next == target { 68 | let target_next = &target.as_ref()?.next; 69 | root.as_mut()?.next = target_next.clone(); 70 | break; 71 | } 72 | root = &mut root.as_mut()?.next; 73 | } 74 | phead?.next 75 | } 76 | // @lc code=end 77 | -------------------------------------------------------------------------------- /linkList/medium/remove_nth_from_end/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /linkList/medium/remove_zero_sum_sublists/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /linkList/medium/remove_zero_sum_sublists/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /linkList/medium/remove_zero_sum_sublists/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /linkList/medium/rotate_right/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /linkList/medium/rotate_right/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /linkList/medium/rotate_right/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=61 lang=rust 3 | * 4 | * [61] 旋转链表 5 | */ 6 | // Definition for singly-linked list. 7 | #[derive(PartialEq, Eq, Clone, Debug)] 8 | pub struct ListNode { 9 | pub val: i32, 10 | pub next: Option>, 11 | } 12 | 13 | impl ListNode { 14 | #[inline] 15 | fn new(val: i32) -> Self { 16 | ListNode { next: None, val } 17 | } 18 | } 19 | struct Solution {} 20 | // @lc code=start 21 | // Definition for singly-linked list. 22 | // #[derive(PartialEq, Eq, Clone, Debug)] 23 | // pub struct ListNode { 24 | // pub val: i32, 25 | // pub next: Option> 26 | // } 27 | // 28 | // impl ListNode { 29 | // #[inline] 30 | // fn new(val: i32) -> Self { 31 | // ListNode { 32 | // next: None, 33 | // val 34 | // } 35 | // } 36 | // } 37 | impl Solution { 38 | pub fn rotate_right(mut head: Option>, k: i32) -> Option> { 39 | // rust 链表无法成环,拆成两个链表再连接 40 | if head.is_none() { 41 | return head; 42 | } 43 | let mut len = 0; 44 | let mut head_refer = &head; 45 | while head_refer.as_ref().is_some() { 46 | // 记录链表长度 47 | len += 1; 48 | head_refer = &head_refer.as_ref()?.next; 49 | } 50 | let offset = k % len; 51 | if offset == 0 { 52 | return head; 53 | } 54 | let mut head_mut_refer = &mut head; 55 | while len - offset != 1 { 56 | len -= 1; 57 | head_mut_refer = &mut head_mut_refer.as_mut()?.next; 58 | } 59 | // right = 4->5 head = 1->2->3 60 | let mut right = head_mut_refer.as_mut()?.next.take(); 61 | let mut right_mut_refer = &mut right; 62 | while right_mut_refer.as_ref()?.next.is_some() { 63 | // 找到 right 的尾部 64 | right_mut_refer = &mut right_mut_refer.as_mut()?.next; 65 | } 66 | right_mut_refer.as_mut()?.next = head; 67 | right 68 | } 69 | } 70 | // @lc code=end 71 | -------------------------------------------------------------------------------- /linkList/medium/rotate_right/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /linkList/medium/swap_pairs/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /linkList/medium/swap_pairs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /linkList/medium/swap_pairs/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Definition for singly-linked list. 2 | #[derive(PartialEq, Eq, Clone, Debug)] 3 | pub struct ListNode { 4 | pub val: i32, 5 | pub next: Option>, 6 | } 7 | 8 | impl ListNode { 9 | #[inline] 10 | fn new(val: i32) -> Self { 11 | ListNode { next: None, val } 12 | } 13 | } 14 | 15 | struct Solution {} 16 | 17 | // 给定 1->2->3->4, 你应该返回 2->1->4->3. 18 | impl Solution { 19 | pub fn swap_pairs(mut head: Option>) -> Option> { 20 | if head.is_none() { 21 | return head; 22 | } 23 | let mut l1 = head; 24 | let mut result = ListNode::new(0); 25 | let mut res = &mut result; 26 | while let Some(mut l1_node) = l1 { 27 | l1 = l1_node.next.take(); // 使用take获取所有权,l1 = 2->3->4, l1_node = 1 此时l1_node.next=None 28 | if let Some(mut l2_node) = l1 { 29 | l1 = l2_node.next.take(); // l1 = 3->4, l2 = 2, 此时l2_node.next=None 30 | l2_node.next = Some(l1_node); // l2 = 2->1 31 | res.next = Some(l2_node); // res = 0->2->1, 32 | res = res.next.as_mut().unwrap().next.as_mut().unwrap(); // res = 1, res指向末尾 33 | } else { 34 | // 走到这里说明总的节点个数为奇数个, l1为最后一个节点,没有下一个节点。直接将l1添加到末尾 35 | res.next = Some(l1_node); 36 | res = res.next.as_mut().unwrap(); 37 | } 38 | } 39 | result.next 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /linkList/medium/swap_pairs/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | assert_eq!(100i32.wrapping_div_euclid(10), 10); 3 | assert_eq!((-128i32).wrapping_div_euclid(1), -128); 4 | let sum: i64 = 100; 5 | assert_eq!(sum.wrapping_rem(10), 0); 6 | } 7 | -------------------------------------------------------------------------------- /others/easy/MinStack/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/easy/MinStack/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/easy/MinStack/src/lib.rs: -------------------------------------------------------------------------------- 1 | // 定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。 2 | 3 | // 4 | 5 | // 示例: 6 | 7 | // MinStack minStack = new MinStack(); 8 | // minStack.push(-2); 9 | // minStack.push(0); 10 | // minStack.push(-3); 11 | // minStack.min(); --> 返回 -3. 12 | // minStack.pop(); 13 | // minStack.top(); --> 返回 0. 14 | // minStack.min(); --> 返回 -2. 15 | 16 | // 来源:力扣(LeetCode) 17 | // 链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof 18 | // 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 19 | struct MinStack { 20 | top: Option, // 栈顶指针 21 | stack: Vec, 22 | min_stack: Vec, 23 | } 24 | 25 | /** 26 | * `&self` means the method takes an immutable reference. 27 | * If you need a mutable reference, change it to `&mut self` instead. 28 | */ 29 | impl MinStack { 30 | /** initialize your data structure here. */ 31 | fn new() -> Self { 32 | return MinStack { 33 | stack: vec![], 34 | top: None, 35 | min_stack: vec![], 36 | }; 37 | } 38 | 39 | fn push(&mut self, x: i32) { 40 | self.stack.push(x); 41 | self.top = Some(x); 42 | if self.min_stack.len() == 0 || x <= self.min_stack[self.min_stack.len() - 1] { 43 | self.min_stack.push(x) 44 | } 45 | } 46 | 47 | fn pop(&mut self) { 48 | if self.stack.pop().unwrap() == self.min_stack[self.min_stack.len() - 1] { 49 | self.min_stack.pop(); 50 | } 51 | if self.stack.len() != 0 { 52 | self.top = Some(self.stack[self.stack.len() - 1]); // 栈顶指针 -1 53 | } else { 54 | self.top = None 55 | } 56 | } 57 | 58 | fn top(&self) -> i32 { 59 | self.top.unwrap() 60 | } 61 | 62 | fn min(&self) -> i32 { 63 | self.min_stack[self.min_stack.len() - 1] 64 | } 65 | } 66 | 67 | // /** 68 | // * Your MinStack object will be instantiated and called as such: 69 | // * let obj = MinStack::new(); 70 | // * obj.push(x); 71 | // * obj.pop(); 72 | // * let ret_3: i32 = obj.top(); 73 | // * let ret_4: i32 = obj.min(); 74 | // */ 75 | -------------------------------------------------------------------------------- /others/easy/MyQueue/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/easy/MyQueue/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/easy/MyStack/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/easy/MyStack/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/easy/build_array/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/easy/build_array/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/easy/build_array/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1441 lang=rust 3 | * 4 | * [1441] 用栈操作构建数组 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | impl Solution { 9 | // pub fn build_array(target: Vec, n: i32) -> Vec { 10 | // let mut v = vec![]; 11 | // if n == 0 { 12 | // return v; 13 | // } 14 | // for i in 1..=n { 15 | // if target[target.len() - 1] == target.len() as i32 && target[target.len() - 1] < i { 16 | // break; 17 | // } 18 | // let index = target.iter().position(|&r| r == i); 19 | // if index.is_none() { 20 | // v.push("Push".to_string()); 21 | // v.push("Pop".to_string()) 22 | // } else { 23 | // v.push("Push".to_string()); 24 | // } 25 | // } 26 | // v 27 | // } 28 | pub fn build_array(target: Vec, n: i32) -> Vec { 29 | let mut v = vec![]; 30 | for i in 1..=target[target.len() - 1] { 31 | let index = target.iter().position(|&r| r == i); 32 | if index.is_none() { 33 | v.push("Push".to_string()); 34 | v.push("Pop".to_string()) 35 | } else { 36 | v.push("Push".to_string()); 37 | } 38 | } 39 | v 40 | } 41 | } 42 | // @lc code=end 43 | -------------------------------------------------------------------------------- /others/easy/construct2_d_array/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/easy/construct2_d_array/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/easy/construct2_d_array/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=2022 lang=rust 3 | * 4 | * [2022] 将一维数组转变成二维数组 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | impl Solution { 9 | pub fn construct2_d_array(original: Vec, m: i32, n: i32) -> Vec> { 10 | let sum = n * m; 11 | if original.len() != sum as usize { 12 | return vec![]; 13 | }; 14 | let (m, n) = (m as usize, n as usize); 15 | let mut v = vec![]; 16 | let mut foo = vec![]; 17 | for i in 0..original.len() { 18 | foo.push(original[i]); 19 | if foo.len() == n { 20 | v.push(foo); 21 | foo = vec![] 22 | } 23 | } 24 | v 25 | } 26 | } 27 | // @lc code=end 28 | -------------------------------------------------------------------------------- /others/easy/exchange/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/easy/exchange/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/easy/exchange/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | 3 | impl Solution { 4 | pub fn exchange(mut nums: Vec) -> Vec { 5 | if nums.len() == 0 { 6 | return nums; 7 | } 8 | let mut left = 0; 9 | let mut right = nums.len() - 1; 10 | while left != right { 11 | if nums[left] % 2 != 0 { 12 | left += 1; 13 | continue; 14 | } 15 | if nums[right] % 2 == 0 { 16 | right -= 1; 17 | continue; 18 | } 19 | let temp = nums[right]; 20 | nums[right] = nums[left]; 21 | nums[left] = temp; 22 | } 23 | println!("{:?}", nums); 24 | nums 25 | } 26 | } 27 | 28 | #[cfg(test)] 29 | mod tests { 30 | use super::*; 31 | 32 | #[test] 33 | fn tests() { 34 | Solution::exchange(vec![1, 2, 3, 4]); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /others/easy/find_judge/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/easy/find_judge/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/easy/find_judge/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=997 lang=rust 3 | * 4 | * [997] 找到小镇的法官 5 | */ 6 | struct Solution {} 7 | 8 | // @lc code=start 9 | impl Solution { 10 | pub fn find_judge(n: i32, trust: Vec>) -> i32 { 11 | let mut in_degree: Vec = vec![0; n as usize]; 12 | let mut out_degree: Vec = vec![0; n as usize]; 13 | trust.iter().for_each(|v| { 14 | in_degree[(v[1] - 1) as usize] = in_degree[(v[1] - 1) as usize] + 1; 15 | out_degree[(v[0] - 1) as usize] = out_degree[(v[0] - 1) as usize] + 1; 16 | }); 17 | let mut res: i32 = -1; 18 | 19 | in_degree.iter().enumerate().for_each(|(i, val)| { 20 | if *val == n - 1 && out_degree[i] == 0 { 21 | res = (i + 1) as i32; 22 | } 23 | }); 24 | 25 | return res; 26 | } 27 | } 28 | // @lc code=end 29 | 30 | #[cfg(test)] 31 | mod test { 32 | use super::*; 33 | 34 | #[test] 35 | fn tests() { 36 | println!( 37 | "{}", 38 | Solution::find_judge(3, vec![vec![1, 3], vec![2, 3], vec![3, 1]]) 39 | ) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /others/easy/generate/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/easy/generate/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/easy/generate/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=118 lang=rust 3 | * 4 | * [118] 杨辉三角 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | impl Solution { 9 | pub fn generate(num_rows: i32) -> Vec> { 10 | let mut v = vec![vec![1]; num_rows as usize]; 11 | for i in 2..=num_rows { 12 | let mut current_val = vec![1; i as usize]; 13 | let pre_val = &v[(i - 2) as usize]; 14 | for j in 1..=(current_val.len() - 2) { 15 | current_val[j as usize] = pre_val[j] + pre_val[j - 1] 16 | } 17 | current_val[(i-1) as usize] =1; 18 | v[(i-1) as usize]=current_val; 19 | } 20 | v 21 | } 22 | } 23 | // @lc code=end 24 | 25 | #[cfg(test)] 26 | 27 | mod tests { 28 | use super::*; 29 | #[test] 30 | fn tests() { 31 | println!("{:?}", Solution::generate(5)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /others/easy/is_subsequence/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/easy/is_subsequence/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/easy/is_subsequence/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=392 lang=rust 3 | * 4 | * [392] 判断子序列 5 | */ 6 | 7 | struct Solution {} 8 | // @lc code=start 9 | impl Solution { 10 | pub fn is_subsequence(s: String, t: String) -> bool { 11 | let mut _t = t.clone(); 12 | for i in s.chars() { 13 | let index = _t.find(i); 14 | if index.is_some() { 15 | let index_val = index.unwrap(); 16 | let len = _t.chars().count(); 17 | _t = _t[index_val + 1..len].to_string(); 18 | } else { 19 | return false; 20 | } 21 | } 22 | true 23 | } 24 | } 25 | // @lc code=end 26 | #[cfg(test)] 27 | mod tests { 28 | use super::*; 29 | 30 | #[test] 31 | fn tests() { 32 | println!( 33 | "{:?}", 34 | Solution::is_subsequence("aaaaa".to_string(), "baaa".to_string()) 35 | ) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /others/easy/shortest_to_char/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/easy/shortest_to_char/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/easy/shortest_to_char/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=821 lang=rust 3 | * 4 | * [821] 字符的最短距离 5 | */ 6 | struct Solution {} 7 | 8 | // @lc code=start 9 | use std::i32::MAX; 10 | impl Solution { 11 | pub fn shortest_to_char(s: String, c: char) -> Vec { 12 | let mut arr = s.split("").collect::>(); 13 | arr = arr[1..arr.len() - 1].to_vec(); 14 | let mut ans = vec![0; arr.len()]; 15 | let mut pre: i32 = MAX; 16 | for (i, val) in arr.iter().enumerate() { 17 | if *val == c.to_string() { 18 | pre = i as i32 19 | } 20 | ans[i] = (i as i32 - pre).abs() 21 | } 22 | pre = MAX; 23 | for (i, _) in arr.iter().enumerate().rev() { 24 | if arr[i] == c.to_string() { 25 | pre = i as i32 26 | } 27 | ans[i] = ans[i].min((i as i32 - pre).abs()) 28 | } 29 | return ans; 30 | } 31 | } 32 | // @lc code=end 33 | 34 | #[cfg(test)] 35 | mod tests { 36 | use super::*; 37 | 38 | #[test] 39 | fn tests() { 40 | println!( 41 | "{:?}", 42 | Solution::shortest_to_char(String::from("aaab"), 'b') 43 | ); 44 | println!( 45 | "{:?}", 46 | Solution::shortest_to_char(String::from("loveleetcode"), 'e') 47 | ); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /others/hard/first_missing_positive/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/hard/first_missing_positive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/hard/first_missing_positive/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=41 lang=rust 3 | * 4 | * [41] 缺失的第一个正数 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | use std::cmp::max; 9 | 10 | impl Solution { 11 | pub fn first_missing_positive(nums: Vec) -> i32 { 12 | if nums.len() == 0 { 13 | return 1; 14 | } 15 | let mut v: Vec = vec![-1; nums.len()]; 16 | let mut MAX = 0; 17 | for i in nums { 18 | if i > 0 && i < v.len() as i32 { 19 | v[i as usize] = 1; 20 | } 21 | MAX = max(MAX, i) 22 | } 23 | for i in 1..v.len() { 24 | if v[i] < 0 { 25 | return i as i32; 26 | } 27 | } 28 | return if v.len() >= MAX as usize { 29 | MAX + 1 30 | } else { 31 | v.len() as i32 32 | }; 33 | } 34 | } 35 | // @lc code=end 36 | #[cfg(test)] 37 | mod tests { 38 | use super::*; 39 | 40 | #[test] 41 | fn tests() { 42 | let nums: Vec = vec![2]; 43 | println!("{:?}", Solution::first_missing_positive(nums)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /others/medium/find_radius/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/medium/find_radius/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/medium/find_radius/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=475 lang=rust 3 | * 4 | * [475] 供暖器 5 | */ 6 | 7 | struct Solution {} 8 | // @lc code=start 9 | impl Solution { 10 | pub fn find_radius(houses: Vec, mut heaters: Vec) -> i32 { 11 | let mut res = i32::MIN; 12 | heaters.sort_by(|a, b| a.partial_cmp(b).unwrap()); 13 | houses.iter().for_each(|h| { 14 | let distance = (Solution::binary_search_left(&heaters, h) - h) 15 | .abs() 16 | .min((Solution::binary_search_right(&heaters, h) - h).abs()); 17 | res = res.max(distance); 18 | }); 19 | res 20 | } 21 | pub fn binary_search_left(nums: &Vec, target: &i32) -> i32 { 22 | // 找到距离 target 最近的左边距离 23 | let (mut left, mut right) = (0, nums.len() - 1); 24 | while left < right { 25 | let mid = left + (right - left) / 2; 26 | if &nums[mid] >= target { 27 | right = mid 28 | } else { 29 | left = mid + 1 30 | } 31 | } 32 | nums[left] 33 | } 34 | pub fn binary_search_right(nums: &Vec, target: &i32) -> i32 { 35 | // 找到距离 target 最近的右边距离 36 | let (mut left, mut right) = (0, nums.len() - 1); 37 | while left < right { 38 | let mid = left + (right - left + 1) / 2; 39 | if &nums[mid] <= target { 40 | left = mid 41 | } else { 42 | right = mid - 1 43 | } 44 | } 45 | nums[left] 46 | } 47 | } 48 | // @lc code=end 49 | 50 | #[cfg(test)] 51 | mod tests { 52 | use super::*; 53 | #[test] 54 | fn name() { 55 | println!("{:?}", Solution::find_radius(vec![1, 2, 3, 4], vec![1, 4])) 56 | // println!("{:?}", Solution::binary_search(&vec![1, 2, 3], &2)); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /others/medium/increasing_triplet/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/medium/increasing_triplet/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/medium/increasing_triplet/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=334 lang=rust 3 | * 4 | * [334] 递增的三元子序列 5 | */ 6 | 7 | struct Solution {} 8 | 9 | // @lc code=start 10 | impl Solution { 11 | pub fn increasing_triplet(nums: Vec) -> bool { 12 | let mut left_min = vec![i32::MAX; nums.len()]; 13 | let mut right_max = vec![i32::MIN; nums.len()]; 14 | let mut foo = nums[0]; 15 | for i in 1..nums.len() { 16 | left_min[i] = if foo < nums[i] { 17 | foo 18 | } else { 19 | foo = nums[i]; 20 | nums[i] 21 | } 22 | } 23 | let mut foo = nums[nums.len() - 1]; 24 | for i in (1..nums.len()).rev() { 25 | right_max[i] = if foo > nums[i] { 26 | foo 27 | } else { 28 | foo = nums[i]; 29 | nums[i] 30 | } 31 | } 32 | for i in 1..nums.len() { 33 | if nums[i] > left_min[i] && nums[i] < right_max[i] { 34 | return true; 35 | } 36 | } 37 | false 38 | } 39 | } 40 | // @lc code=end 41 | #[cfg(test)] 42 | mod tests { 43 | use super::*; 44 | 45 | #[test] 46 | fn tests() { 47 | assert_eq!(Solution::increasing_triplet(vec![1, 3, 5, 4, 7]), true); 48 | assert_eq!(Solution::increasing_triplet(vec![5, 4, 3, 2, 1]), false) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /others/medium/k_smallest_pairs/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/medium/k_smallest_pairs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/medium/k_smallest_pairs/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=373 lang=rust 3 | * 4 | * [373] 查找和最小的K对数字 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | use std::cmp::Reverse; 9 | use std::collections::BinaryHeap; 10 | 11 | impl Solution { 12 | pub fn k_smallest_pairs(nums1: Vec, nums2: Vec, mut k: i32) -> Vec> { 13 | let mut res = vec![]; 14 | let mut heap = BinaryHeap::new(); 15 | for i in 0..nums1.len() { 16 | heap.push((Reverse(nums1[i] + nums2[0]), i, 0)) 17 | } 18 | while let Some((_, i, j)) = heap.pop() { 19 | if k <= 0 { 20 | break; 21 | } 22 | res.push(vec![nums1[i], nums2[j]]); 23 | if j + 1 < nums2.len() { 24 | heap.push((Reverse(nums1[i] + nums2[j + 1]), i, j + 1)); 25 | } 26 | k -= 1; 27 | } 28 | res 29 | } 30 | } 31 | // @lc code=end 32 | #[cfg(test)] 33 | mod tests { 34 | use super::*; 35 | 36 | #[test] 37 | fn tests() { 38 | Solution::k_smallest_pairs(vec![1, 1, 2], vec![1, 2, 3], 8); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /others/medium/last_remaining/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/medium/last_remaining/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/medium/max_area/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/medium/max_area/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/medium/max_area/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=11 lang=rust 3 | * 4 | * [11] 盛最多水的容器 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | impl Solution { 9 | pub fn max_area(height: Vec) -> i32 { 10 | let (mut left, mut right, mut res) = (0, height.len() - 1, 0); 11 | while left < right { 12 | res = res.max(height[left].min(height[right]) * (right - left) as i32); 13 | if height[left] < height[right] { 14 | left = left + 1; 15 | } else { 16 | right = right - 1; 17 | } 18 | } 19 | return res; 20 | } 21 | } 22 | // @lc code=end 23 | 24 | #[cfg(test)] 25 | mod tests { 26 | use super::*; 27 | 28 | #[test] 29 | fn tests() { 30 | Solution::max_area(vec![1, 8, 6, 2, 5, 4, 8, 3, 7]); 31 | Solution::max_area(vec![1, 1]); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /others/medium/max_increase_keeping_skyline/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /others/medium/max_increase_keeping_skyline/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /others/medium/max_increase_keeping_skyline/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=807 lang=rust 3 | * 4 | * [807] 保持城市天际线 5 | */ 6 | struct Solution {} 7 | 8 | // @lc code=start 9 | impl Solution { 10 | pub fn max_increase_keeping_skyline(grid: Vec>) -> i32 { 11 | let n = grid.len(); 12 | if n == 0 { 13 | return 0; 14 | }; 15 | let mut res = 0; 16 | let row_max = grid 17 | .iter() 18 | .map(|val| *val.iter().max().unwrap()) 19 | .collect::>(); 20 | let mut col_max: Vec = vec![-1; n]; 21 | grid.iter().enumerate().for_each(|(i, row)| { 22 | row.iter().enumerate().for_each(|(j, val)| { 23 | let max = val.max(&col_max[j]); 24 | col_max[j] = *max; 25 | }) 26 | }); 27 | grid.iter().enumerate().for_each(|(i, row)| { 28 | row 29 | .iter() 30 | .enumerate() 31 | .for_each(|(j, _)| res += row_max[i].min(col_max[j]) - grid[i][j]) 32 | }); 33 | return res; 34 | } 35 | } 36 | // @lc code=end 37 | 38 | #[cfg(test)] 39 | mod tests { 40 | use super::*; 41 | 42 | #[test] 43 | fn tests() { 44 | let grid = vec![ 45 | vec![3, 0, 8, 4], 46 | vec![2, 4, 5, 7], 47 | vec![9, 2, 6, 3], 48 | vec![0, 3, 1, 0], 49 | ]; 50 | Solution::max_increase_keeping_skyline(grid); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tree/easy/average_of_levels/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/average_of_levels/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/average_of_levels/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | 20 | use std::cell::RefCell; 21 | use std::collections::VecDeque; 22 | use std::rc::Rc; 23 | 24 | pub fn average_of_levels(mut root: Option>>) -> Vec { 25 | let mut v = vec![]; 26 | if root.is_none() { 27 | return v; 28 | } 29 | let mut queue = VecDeque::new(); 30 | queue.push_front(root); 31 | while queue.len() != 0 { 32 | let mut node_vec = vec![]; 33 | let mut sum: f64 = 0.0; 34 | let mut len = queue.len(); 35 | while queue.len() != 0 { 36 | let node = queue.pop_front().unwrap().unwrap(); 37 | sum += node.borrow().val as f64; 38 | node_vec.push(node); // 将当前队列中的所有元素出队并保存,即当前行的所有元素 39 | } 40 | v.push((sum as f64) / (len as f64)); 41 | for i in &node_vec { 42 | // 把当前行所有元素的下一行元素入队 43 | let mut node = i; 44 | if !node.borrow().left.is_none() { 45 | queue.push_back(node.borrow_mut().left.take()); 46 | } 47 | if !node.borrow().right.is_none() { 48 | queue.push_back(node.borrow_mut().right.take()); 49 | } 50 | } 51 | } 52 | v 53 | } 54 | -------------------------------------------------------------------------------- /tree/easy/average_of_levels/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/binary_tree_paths/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/binary_tree_paths/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/binary_tree_paths/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | 20 | // 输入: 21 | 22 | // 1 23 | // / \ 24 | // 2 3 25 | // \ 26 | // 5 27 | 28 | // 输出: ["1->2->5", "1->3"] 29 | 30 | // 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3 31 | 32 | use std::cell::RefCell; 33 | use std::rc::Rc; 34 | 35 | pub fn binary_tree_paths(root: Option>>) -> Vec { 36 | let mut v = vec![]; 37 | find_leaf(&root, &mut v, None); 38 | v 39 | } 40 | 41 | fn find_leaf(root: &Option>>, v: &mut Vec, str: Option<&mut String>) { 42 | // 递归找到叶子节点记录路径即可 43 | if root.is_none() { 44 | return; 45 | } 46 | let val = &root.as_ref().unwrap().borrow().val.to_string(); 47 | let left = &root.as_ref().unwrap().borrow().left; 48 | let right = &root.as_ref().unwrap().borrow().right; 49 | 50 | let mut res_str; 51 | match str { 52 | None => { 53 | res_str = String::from(""); 54 | } 55 | Some(str) => { 56 | res_str = str.to_string(); 57 | } 58 | } 59 | res_str.push_str(val); 60 | if left.is_none() && right.is_none() { 61 | // 说明当前为叶子节点 62 | v.push(res_str); 63 | return; 64 | } 65 | res_str.push_str("->"); 66 | find_leaf(left, v, Some(&mut res_str)); 67 | find_leaf(right, v, Some(&mut res_str)); 68 | } 69 | -------------------------------------------------------------------------------- /tree/easy/binary_tree_paths/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/convert_bst/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/convert_bst/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/convert_bst/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/find_mode/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/find_mode/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/find_mode/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /tree/easy/find_tilt/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/find_tilt/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/find_tilt/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/is_balanced/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/is_balanced/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/is_balanced/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | 20 | use std::cell::RefCell; 21 | use std::cmp::max; 22 | use std::rc::Rc; 23 | 24 | pub fn is_balanced(root: Option>>) -> bool { 25 | if root.is_none() { 26 | return true; 27 | } 28 | 29 | check(root) 30 | } 31 | 32 | fn check(mut root: Option>>) -> bool { 33 | if root.is_none() { 34 | return true; 35 | } 36 | let left = root.as_mut().unwrap().borrow_mut().left.take(); 37 | let right = root.as_mut().unwrap().borrow_mut().right.take(); 38 | return (get_height(&left) - get_height(&right)).abs() <= 1 && check(left) && check(right); 39 | } 40 | fn get_height(root: &Option>>) -> i32 { 41 | // 获取改节点的最大高度 42 | if root.is_none() { 43 | return 0; 44 | } 45 | let left = &root.as_ref().unwrap().borrow().left; 46 | let right = &root.as_ref().unwrap().borrow().right; 47 | return max(get_height(&left), get_height(&right)) + 1; 48 | } 49 | -------------------------------------------------------------------------------- /tree/easy/is_balanced/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/is_same_tree/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/is_same_tree/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/is_same_tree/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | 20 | struct Solution {} 21 | use std::cell::RefCell; 22 | use std::rc::Rc; 23 | 24 | impl Solution { 25 | pub fn is_same_tree( 26 | mut p: Option>>, 27 | mut q: Option>>, 28 | ) -> bool { 29 | check(p, q) 30 | } 31 | } 32 | fn check(mut p: Option>>, mut q: Option>>) -> bool { 33 | if p.is_none() && q.is_none() { 34 | return true; 35 | } 36 | if p.is_none() || q.is_none() { 37 | return false; 38 | } 39 | 40 | if let Some(p_node) = &p { 41 | let p_left = p_node.borrow_mut().left.take(); 42 | let p_right = p_node.borrow_mut().right.take(); 43 | if let Some(q_node) = &q { 44 | let q_left = q_node.borrow_mut().left.take(); 45 | let q_right = q_node.borrow_mut().right.take(); 46 | return p.as_ref().unwrap().borrow().val == q.as_ref().unwrap().borrow().val 47 | && check(p_left, q_left) 48 | && check(q_right, p_right); 49 | } 50 | } 51 | false 52 | } 53 | -------------------------------------------------------------------------------- /tree/easy/is_same_tree/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/is_subtree/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/is_subtree/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/is_subtree/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/is_symmetric/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/is_symmetric/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/is_symmetric/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | 20 | use std::cell::RefCell; 21 | use std::rc::Rc; 22 | 23 | pub fn is_symmetric(mut root: Option>>) -> bool { 24 | if root.is_none() { 25 | return true; 26 | } 27 | let left = root.as_mut().unwrap().borrow_mut().left.take(); 28 | let right = root.as_mut().unwrap().borrow_mut().right.take(); 29 | return check(left, right); 30 | } 31 | 32 | fn check( 33 | mut node1: Option>>, 34 | mut node2: Option>>, 35 | ) -> bool { 36 | if node1.is_none() && node2.is_none() { 37 | return true; 38 | } 39 | if node1.is_none() || node2.is_none() { 40 | return false; 41 | } 42 | let node1_left = node1.as_mut().unwrap().borrow_mut().left.take(); 43 | let node1_right = node1.as_mut().unwrap().borrow_mut().right.take(); 44 | let node2_left = node2.as_mut().unwrap().borrow_mut().left.take(); 45 | let node2_right = node2.as_mut().unwrap().borrow_mut().right.take(); 46 | return node1.as_ref().unwrap().borrow().val == node2.as_ref().unwrap().borrow().val 47 | && check(node1_left, node2_right) 48 | && check(node2_left, node1_right); 49 | } 50 | -------------------------------------------------------------------------------- /tree/easy/is_symmetric/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/kth_largest/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/kth_largest/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/kth_largest/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | // 给定一棵二叉搜索树,请找出其中第k大的节点。 20 | 21 | // 22 | 23 | // 示例 1: 24 | 25 | // 输入: root = [3,1,4,null,2], k = 1 26 | // 3 27 | // / \ 28 | // 1 4 29 | // \ 30 | //   2 31 | // 输出: 4 32 | 33 | use std::cell::RefCell; 34 | use std::rc::Rc; 35 | 36 | pub fn kth_largest(mut root: Option>>, k: i32) -> i32 { 37 | if root.is_none() { 38 | return 0; 39 | } 40 | let mut v = vec![]; 41 | let mut stack = vec![]; 42 | while stack.len() != 0 || !root.is_none() { 43 | while !root.is_none() { 44 | // 一直添加左子树直到为空 45 | let node = root.unwrap(); 46 | root = node.borrow_mut().left.take(); 47 | stack.push(node); 48 | } 49 | // 从栈中弹出,取节点的右子树 50 | root = stack.pop(); 51 | v.push(root.as_mut().unwrap().borrow().val); 52 | root = root.unwrap().borrow_mut().right.take(); 53 | } 54 | return *v.get(v.len() - k as usize).unwrap(); 55 | } 56 | -------------------------------------------------------------------------------- /tree/easy/kth_largest/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /tree/easy/leaf_similar/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/leaf_similar/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/leaf_similar/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=872 lang=rust 3 | * 4 | * [872] 叶子相似的树 5 | */ 6 | // Definition for a binary tree node. 7 | #[derive(Debug, PartialEq, Eq)] 8 | pub struct TreeNode { 9 | pub val: i32, 10 | pub left: Option>>, 11 | pub right: Option>>, 12 | } 13 | 14 | impl TreeNode { 15 | #[inline] 16 | pub fn new(val: i32) -> Self { 17 | TreeNode { 18 | val, 19 | left: None, 20 | right: None, 21 | } 22 | } 23 | } 24 | struct Solution {} 25 | // @lc code=start 26 | // Definition for a binary tree node. 27 | // #[derive(Debug, PartialEq, Eq)] 28 | // pub struct TreeNode { 29 | // pub val: i32, 30 | // pub left: Option>>, 31 | // pub right: Option>>, 32 | // } 33 | // 34 | // impl TreeNode { 35 | // #[inline] 36 | // pub fn new(val: i32) -> Self { 37 | // TreeNode { 38 | // val, 39 | // left: None, 40 | // right: None 41 | // } 42 | // } 43 | // } 44 | use std::cell::RefCell; 45 | use std::rc::Rc; 46 | impl Solution { 47 | pub fn leaf_similar( 48 | root1: Option>>, 49 | root2: Option>>, 50 | ) -> bool { 51 | let mut leaf_1 = vec![]; 52 | Self::get_leaf(&root1, &mut leaf_1); 53 | let mut leaf_2 = vec![]; 54 | Self::get_leaf(&root2, &mut leaf_2); 55 | if leaf_1.len() != leaf_2.len() { 56 | return false; 57 | } 58 | let mut res = true; 59 | for i in 0..leaf_1.len() { 60 | if leaf_1[i] != leaf_2[i] { 61 | res = false; 62 | break; 63 | } 64 | } 65 | res 66 | } 67 | fn get_leaf(root: &Option>>, v: &mut Vec) { 68 | if root.is_none() { 69 | return; 70 | } 71 | let root_borrow = root.as_ref().unwrap().borrow(); 72 | let left = &root_borrow.left; 73 | let right = &root_borrow.right; 74 | if left.is_none() && right.is_none() { 75 | v.push(root_borrow.val); 76 | return; 77 | } 78 | Self::get_leaf(left, v); 79 | Self::get_leaf(right, v); 80 | } 81 | } 82 | // @lc code=end 83 | -------------------------------------------------------------------------------- /tree/easy/leaf_similar/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/level_order_bottom/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/level_order_bottom/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/level_order_bottom/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | // 输入: [1,null,2,3] 20 | // 1 21 | // \ 22 | // 2 23 | // / 24 | // 3 25 | 26 | // 输出: [1,3,2] 27 | use std::cell::RefCell; 28 | use std::collections::VecDeque; 29 | use std::rc::Rc; 30 | 31 | pub fn level_order_bottom(mut root: Option>>) -> Vec> { 32 | let mut v = vec![]; 33 | if root.is_none() { 34 | return v; 35 | } 36 | let mut queue = VecDeque::new(); 37 | queue.push_front(root); 38 | while queue.len() != 0 { 39 | let mut node_vec = vec![]; 40 | let mut val_vec = vec![]; 41 | while queue.len() != 0 { 42 | let node = queue.pop_front().unwrap().unwrap(); 43 | val_vec.push(node.borrow().val); // 记录当前行的所有元素的val 44 | node_vec.push(node); // 将当前队列中的所有元素出队并保存,即当前行的所有元素 45 | } 46 | v.push(val_vec); 47 | for i in &node_vec { 48 | // 把当前行所有元素的下一行元素入队 49 | let mut node = i; 50 | if !node.borrow().left.is_none() { 51 | queue.push_back(node.borrow_mut().left.take()); 52 | } 53 | if !node.borrow().right.is_none() { 54 | queue.push_back(node.borrow_mut().right.take()); 55 | } 56 | } 57 | } 58 | let mut i = 0; 59 | let mut res = vec![]; 60 | while i < v.len() { 61 | res.push(v[v.len() - i - 1].clone()); 62 | i += 1; 63 | } 64 | res 65 | } 66 | -------------------------------------------------------------------------------- /tree/easy/level_order_bottom/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut v = [[1, 12], [2, 1], [3, 2]]; 3 | v.reverse(); 4 | println!("{:?}", v); 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/min_depth/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/min_depth/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/min_depth/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | 20 | // 给定二叉树 [3,9,20,null,null,15,7], 21 | 22 | // 3 23 | // / \ 24 | // 9 20 25 | // / \ 26 | // 15 7 27 | // 返回它的最小深度  2. 28 | 29 | use std::cell::RefCell; 30 | use std::rc::Rc; 31 | 32 | pub fn min_depth(root: Option>>) -> i32 { 33 | if root.is_none() { 34 | return 0; 35 | } 36 | let mut v = vec![]; 37 | find_leaf(&root, &mut v, Some(1)); 38 | let mut min = v.get(0).unwrap(); 39 | for i in &v { 40 | if i < min { 41 | min = i; 42 | } 43 | } 44 | *min 45 | } 46 | 47 | fn find_leaf(root: &Option>>, v: &mut Vec, depth: Option) { 48 | // 递归找到叶子节点记录路径即可 49 | if root.is_none() { 50 | return; 51 | } 52 | let left = &root.as_ref().unwrap().borrow().left; 53 | let right = &root.as_ref().unwrap().borrow().right; 54 | 55 | let mut depth = depth.unwrap(); 56 | if left.is_none() && right.is_none() { 57 | // 说明当前为叶子节点 58 | v.push(depth); 59 | return; 60 | } 61 | depth += 1; 62 | 63 | find_leaf(left, v, Some(depth)); 64 | find_leaf(right, v, Some(depth)); 65 | } 66 | -------------------------------------------------------------------------------- /tree/easy/min_depth/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/min_diff_in_bst/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/min_diff_in_bst/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/min_diff_in_bst/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | // 输入: root = [4,2,6,1,3,null,null] 20 | // 输出: 1 21 | // 解释: 22 | // 注意,root是树节点对象(TreeNode object),而不是数组。 23 | 24 | // 给定的树 [4,2,6,1,3,null,null] 可表示为下图: 25 | 26 | // 4 27 | // / \ 28 | // 2 6 29 | // / \ 30 | // 1 3 31 | 32 | // 最小的差值是 1, 它是节点1和节点2的差值, 也是节点3和节点2的差值。 33 | 34 | use std::cell::RefCell; 35 | use std::rc::Rc; 36 | 37 | pub fn min_diff_in_bst(mut root: Option>>) -> i32 { 38 | if root.is_none() { 39 | return 0; 40 | } 41 | let mut v = vec![]; 42 | let mut stack = vec![]; 43 | while stack.len() != 0 || !root.is_none() { 44 | while !root.is_none() { 45 | // 一直添加左子树直到为空 46 | let node = root.unwrap(); 47 | root = node.borrow_mut().left.take(); 48 | stack.push(node); 49 | } 50 | // 从栈中弹出,取节点的右子树 51 | root = stack.pop(); 52 | v.push(root.as_mut().unwrap().borrow().val); 53 | root = root.unwrap().borrow_mut().right.take(); 54 | } 55 | let mut min = 999; 56 | let mut i = 0; 57 | while i + 1 < v.len() { 58 | let res = v.get(i + 1).unwrap() - v.get(i).unwrap(); 59 | if res < min { 60 | min = res 61 | } 62 | i += 1; 63 | } 64 | min 65 | } 66 | -------------------------------------------------------------------------------- /tree/easy/min_diff_in_bst/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/range_sum_bst/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/range_sum_bst/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/range_sum_bst/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | // 输入:root = [10,5,15,3,7,null,18], L = 7, R = 15 20 | // 输出:32 21 | 22 | use std::cell::RefCell; 23 | use std::rc::Rc; 24 | 25 | pub fn range_sum_bst(mut root: Option>>, l: i32, r: i32) -> i32 { 26 | let mut left = 0 as usize; 27 | let mut right = 0 as usize; 28 | if root.is_none() { 29 | return 0; 30 | } 31 | let mut v = vec![]; 32 | let mut stack = vec![]; 33 | while stack.len() != 0 || !root.is_none() { 34 | while !root.is_none() { 35 | // 一直添加左子树直到为空 36 | let node = root.unwrap(); 37 | root = node.borrow_mut().left.take(); 38 | stack.push(node); 39 | } 40 | // 从栈中弹出,取节点的右子树 41 | root = stack.pop(); 42 | if root.as_mut().unwrap().borrow().val == l { 43 | left = v.len() as usize; 44 | } 45 | if root.as_mut().unwrap().borrow().val == r { 46 | right = v.len() as usize; 47 | } 48 | v.push(root.as_mut().unwrap().borrow().val); 49 | root = root.unwrap().borrow_mut().right.take(); 50 | } 51 | let v = &v[left..(right + 1)]; 52 | v.iter().sum() 53 | } 54 | -------------------------------------------------------------------------------- /tree/easy/range_sum_bst/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /tree/easy/search_bst/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/search_bst/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/search_bst/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | 20 | // 给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。 21 | 22 | // 例如, 23 | 24 | // 给定二叉搜索树: 25 | 26 | // 4 27 | // / \ 28 | // 2 7 29 | // / \ 30 | // 1 3 31 | 32 | // 和值: 2 33 | // 你应该返回如下子树: 34 | 35 | // 2 36 | // / \ 37 | // 1 3 38 | 39 | use std::cell::RefCell; 40 | use std::rc::Rc; 41 | 42 | impl Solution { 43 | pub fn search_bst( 44 | mut root: Option>>, 45 | val: i32, 46 | ) -> Option>> { 47 | if root.is_none() { 48 | return root; 49 | } 50 | let node_val = root.as_ref().unwrap().borrow().val; 51 | if node_val == val { 52 | return root; 53 | } 54 | let left = root.as_ref().unwrap().borrow_mut().left.take(); 55 | let right = root.as_ref().unwrap().borrow_mut().right.take(); 56 | if node_val > val { 57 | return Self::search_bst(left, val); 58 | } else { 59 | return Self::search_bst(right, val); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /tree/easy/search_bst/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/sorted_array_to_bst/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /tree/easy/sorted_array_to_bst/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/sorted_array_to_bst/src/322.lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=322 lang=rust 3 | * 4 | * [322] 零钱兑换 5 | */ 6 | 7 | // @lc code=start 8 | impl Solution { 9 | pub fn coin_change(coins: Vec, amount: i32) -> i32 { 10 | 11 | } 12 | } 13 | // @lc code=end 14 | 15 | -------------------------------------------------------------------------------- /tree/easy/sorted_array_to_bst/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=108 lang=rust 3 | * 4 | * [108] 将有序数组转换为二叉搜索树 5 | */ 6 | 7 | struct Solution {} 8 | #[derive(Debug, PartialEq, Eq)] 9 | pub struct TreeNode { 10 | pub val: i32, 11 | pub left: Option>>, 12 | pub right: Option>>, 13 | } 14 | 15 | impl TreeNode { 16 | #[inline] 17 | pub fn new(val: i32) -> Self { 18 | TreeNode { 19 | val, 20 | left: None, 21 | right: None, 22 | } 23 | } 24 | } 25 | // @lc code=start 26 | // Definition for a binary tree node. 27 | // #[derive(Debug, PartialEq, Eq)] 28 | // pub struct TreeNode { 29 | // pub val: i32, 30 | // pub left: Option>>, 31 | // pub right: Option>>, 32 | // } 33 | // 34 | // impl TreeNode { 35 | // #[inline] 36 | // pub fn new(val: i32) -> Self { 37 | // TreeNode { 38 | // val, 39 | // left: None, 40 | // right: None 41 | // } 42 | // } 43 | // } 44 | use std::cell::RefCell; 45 | use std::rc::Rc; 46 | impl Solution { 47 | pub fn sorted_array_to_bst(nums: Vec) -> Option>> { 48 | if nums.len() == 0 { 49 | return None; 50 | } 51 | let mut root_index = 0; 52 | let mut root = if nums.len() % 2 != 0 { 53 | root_index = nums.len() / 2; 54 | create_node(nums[root_index]) 55 | } else { 56 | root_index = nums.len() / 2 - 1; 57 | create_node(nums[root_index]) 58 | }; 59 | root.as_mut().unwrap().borrow_mut().right = 60 | Self::sorted_array_to_bst(nums[root_index + 1..nums.len()].to_vec()); 61 | root.as_mut().unwrap().borrow_mut().left = 62 | Self::sorted_array_to_bst(nums[0..root_index].to_vec()); 63 | root 64 | } 65 | } 66 | fn create_node(val: i32) -> Option>> { 67 | Some(Rc::new(RefCell::new(TreeNode::new(val)))) 68 | } 69 | // @lc code=end 70 | 71 | #[cfg(test)] 72 | mod tests { 73 | use super::*; 74 | 75 | #[test] 76 | fn tests() { 77 | Solution::sorted_array_to_bst(vec![0, 1, 2, 3, 4, 5, 6]); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /tree/easy/sum_of_left_leaves/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/sum_of_left_leaves/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/sum_of_left_leaves/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | // 计算给定二叉树的所有左叶子之和。 20 | 21 | // 3 22 | // / \ 23 | // 9 20 24 | // / \ 25 | // 15 7 26 | 27 | // 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24 28 | 29 | use std::cell::RefCell; 30 | use std::rc::Rc; 31 | 32 | pub fn sum_of_left_leaves(root: Option>>) -> i32 { 33 | let mut v = vec![]; 34 | find_leaf(&root, &mut v, "root".to_string()); 35 | let mut sum = 0; 36 | for i in &v { 37 | sum += i; 38 | } 39 | sum 40 | } 41 | 42 | fn find_leaf(root: &Option>>, v: &mut Vec, node_type: String) { 43 | // 递归找到叶子节点记录路径即可 44 | if root.is_none() { 45 | return; 46 | } 47 | let val = &root.as_ref().unwrap().borrow().val; 48 | let left = &root.as_ref().unwrap().borrow().left; 49 | let right = &root.as_ref().unwrap().borrow().right; 50 | 51 | if left.is_none() && right.is_none() { 52 | // 说明当前为左叶子节点 53 | if node_type == "left" { 54 | v.push(*val); 55 | } 56 | return; 57 | } 58 | find_leaf(left, v, "left".to_string()); 59 | find_leaf(right, v, "right".to_string()); 60 | } 61 | -------------------------------------------------------------------------------- /tree/easy/sum_of_left_leaves/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/easy/trim_bst/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/easy/trim_bst/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/easy/trim_bst/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | 20 | // 给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。 21 | 22 | // 例如, 23 | 24 | // 给定二叉搜索树: 25 | 26 | // 4 27 | // / \ 28 | // 2 7 29 | // / \ 30 | // 1 3 31 | 32 | // 和值: 2 33 | // 你应该返回如下子树: 34 | 35 | // 2 36 | // / \ 37 | // 1 3 38 | 39 | use std::cell::RefCell; 40 | use std::rc::Rc; 41 | 42 | pub fn trim_bst( 43 | mut root: Option>>, 44 | l: i32, 45 | r: i32, 46 | ) -> Option>> { 47 | cut_branch(&mut root, l, r); 48 | root 49 | } 50 | 51 | fn cut_branch(mut root: &mut Option>>, l: i32, r: i32) { 52 | let val = root.as_mut().unwrap().borrow_mut().val; 53 | let mut left = root.as_mut().unwrap().borrow_mut().left.take(); 54 | let mut right = root.as_mut().unwrap().borrow_mut().right.take(); 55 | if val < l || val > r { 56 | // if left.is_none() && right.is_none() { 57 | // root = None; 58 | // } 59 | if val < l { 60 | root = &mut right; 61 | } 62 | if val > r { 63 | root = &mut left; 64 | } 65 | } 66 | cut_branch(&mut left, l, r); 67 | cut_branch(&mut right, l, r); 68 | } 69 | -------------------------------------------------------------------------------- /tree/easy/trim_bst/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let a: f64 = 29.0; 3 | let b: f64 = 2.0; 4 | assert_eq!(a / b, 14.5); // 7.0 > 4.0 * 1.0 5 | } 6 | -------------------------------------------------------------------------------- /tree/hard/postorder_traversal/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/hard/postorder_traversal/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/hard/postorder_traversal/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | // 输入: [1,null,2,3] 20 | // 1 21 | // \ 22 | // 2 23 | // / 24 | // 3 25 | 26 | // 输出: [3,2,1] 27 | use std::cell::RefCell; 28 | use std::collections::VecDeque; 29 | use std::rc::Rc; 30 | 31 | pub fn postorder_traversal(mut root: Option>>) -> Vec { 32 | // 这里使用了队列,但是返回结果需要是vector,最后一个遍历返回venctor 33 | let mut queue = VecDeque::new(); 34 | let mut v = vec![]; 35 | if root.is_none() { 36 | return v; 37 | } 38 | let mut stack = vec![root]; 39 | while stack.len() != 0 { 40 | let mut node = stack.pop().unwrap().unwrap(); // stack.pop返回option所以这里需要执行两次unwrap 41 | queue.push_front(node.borrow().val); // 队列入队,相当于数组的unshift方法从左边插入 42 | if !node.borrow().left.is_none() { 43 | stack.push(node.borrow_mut().left.take()) 44 | } 45 | if !node.borrow().right.is_none() { 46 | stack.push(node.borrow_mut().right.take()) 47 | } 48 | } 49 | while queue.len() != 0 { 50 | v.push(queue.pop_front().unwrap()) 51 | } 52 | v 53 | } 54 | -------------------------------------------------------------------------------- /tree/hard/postorder_traversal/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /tree/medium/Trie/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /tree/medium/Trie/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/build_tree/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /tree/medium/build_tree/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/build_tree_postorder/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /tree/medium/build_tree_postorder/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/construct_from_pre_post/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /tree/medium/construct_from_pre_post/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/construct_maximum_binary_tree/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /tree/medium/construct_maximum_binary_tree/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/construct_maximum_binary_tree/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=654 lang=rust 3 | * 4 | * [654] 最大二叉树 5 | */ 6 | // #[derive(Debug, PartialEq, Eq)] 7 | pub struct TreeNode { 8 | pub val: i32, 9 | pub left: Option>>, 10 | pub right: Option>>, 11 | } 12 | 13 | impl TreeNode { 14 | #[inline] 15 | pub fn new(val: i32) -> Self { 16 | TreeNode { 17 | val, 18 | left: None, 19 | right: None, 20 | } 21 | } 22 | } 23 | struct Solution {} 24 | // @lc code=start 25 | // Definition for a binary tree node. 26 | // #[derive(Debug, PartialEq, Eq)] 27 | // pub struct TreeNode { 28 | // pub val: i32, 29 | // pub left: Option>>, 30 | // pub right: Option>>, 31 | // } 32 | // 33 | // impl TreeNode { 34 | // #[inline] 35 | // pub fn new(val: i32) -> Self { 36 | // TreeNode { 37 | // val, 38 | // left: None, 39 | // right: None 40 | // } 41 | // } 42 | // } 43 | use std::cell::RefCell; 44 | use std::rc::Rc; 45 | impl Solution { 46 | pub fn construct_maximum_binary_tree(nums: Vec) -> Option>> { 47 | if nums.len() == 0 { 48 | return None; 49 | } 50 | let index = Self::get_max(&nums); 51 | let mut root = Self::create_node(nums[index]); 52 | let nums_left = nums[0..index].to_vec(); 53 | let nums_right = nums[index + 1..nums.len()].to_vec(); 54 | root.as_mut()?.borrow_mut().left = Self::construct_maximum_binary_tree(nums_left); 55 | root.as_mut()?.borrow_mut().right = Self::construct_maximum_binary_tree(nums_right); 56 | root 57 | } 58 | fn get_max(v: &Vec) -> usize { 59 | let mut index = 0; 60 | let mut MAX = v[index]; 61 | for i in 0..v.len() { 62 | if v[i] > MAX { 63 | MAX = v[i]; 64 | index = i 65 | } 66 | } 67 | index 68 | } 69 | fn create_node(val: i32) -> Option>> { 70 | Some(Rc::new(RefCell::new(TreeNode::new(val)))) 71 | } 72 | } 73 | // @lc code=end 74 | -------------------------------------------------------------------------------- /tree/medium/count_nodes/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /tree/medium/count_nodes/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/flatten/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/medium/flatten/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/flatten/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | impl TreeNode { 9 | #[inline] 10 | pub fn new(val: i32) -> Self { 11 | TreeNode { 12 | val, 13 | left: None, 14 | right: None, 15 | } 16 | } 17 | } 18 | use std::cell::RefCell; 19 | use std::rc::Rc; 20 | 21 | pub fn flatten(mut root: &mut Option>>) { 22 | if root.is_none() { 23 | return; 24 | } 25 | let mut v = vec![]; 26 | let mut stack = vec![]; 27 | let mut root_clone = root.clone(); 28 | while stack.len() != 0 || !root_clone.is_none() { 29 | while !root_clone.is_none() { 30 | // 一直添加左子树直到为空 31 | let node = root_clone.unwrap(); 32 | v.push(node.clone()); 33 | root_clone = node.borrow_mut().left.take(); 34 | stack.push(node); 35 | } 36 | // 从栈中弹出,取节点的右子树 37 | root_clone = stack.pop(); 38 | root_clone = root_clone.unwrap().borrow_mut().right.take(); 39 | } 40 | for i in 1..v.len() { 41 | let pre = &v[i - 1]; 42 | let curr = &v[i]; 43 | pre.as_ref().borrow_mut().left = None; 44 | pre.as_ref().borrow_mut().right = Some(curr.clone()); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /tree/medium/flatten/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /tree/medium/inorder_traversal/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/medium/inorder_traversal/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/inorder_traversal/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | // 输入: [1,null,2,3] 20 | // 1 21 | // \ 22 | // 2 23 | // / 24 | // 3 25 | 26 | // 输出: [1,3,2] 27 | use std::cell::RefCell; 28 | use std::rc::Rc; 29 | 30 | pub fn inorder_traversal(mut root: Option>>) -> Vec { 31 | let mut v = vec![]; 32 | if root.is_none() { 33 | return v; 34 | } 35 | let mut stack = vec![]; 36 | while stack.len() != 0 || !root.is_none() { 37 | while !root.is_none() { 38 | // 一直添加左子树直到为空 39 | let node = root.unwrap(); 40 | root = node.borrow_mut().left.take(); 41 | stack.push(node); 42 | } 43 | // 从栈中弹出,取节点的右子树 44 | root = stack.pop(); 45 | v.push(root.as_mut().unwrap().borrow().val); 46 | root = root.unwrap().borrow_mut().right.take(); 47 | } 48 | v 49 | } 50 | -------------------------------------------------------------------------------- /tree/medium/inorder_traversal/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /tree/medium/is_valid_bst/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /tree/medium/is_valid_bst/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/is_valid_bst/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=98 lang=rust 3 | * 4 | * [98] 验证二叉搜索树 5 | */ 6 | struct Solution {} 7 | #[derive(Debug, PartialEq, Eq)] 8 | pub struct TreeNode { 9 | pub val: i32, 10 | pub left: Option>>, 11 | pub right: Option>>, 12 | } 13 | 14 | impl TreeNode { 15 | #[inline] 16 | pub fn new(val: i32) -> Self { 17 | TreeNode { 18 | val, 19 | left: None, 20 | right: None, 21 | } 22 | } 23 | } 24 | // @lc code=start 25 | // Definition for a binary tree node. 26 | // #[derive(Debug, PartialEq, Eq)] 27 | // pub struct TreeNode { 28 | // pub val: i32, 29 | // pub left: Option>>, 30 | // pub right: Option>>, 31 | // } 32 | // 33 | // impl TreeNode { 34 | // #[inline] 35 | // pub fn new(val: i32) -> Self { 36 | // TreeNode { 37 | // val, 38 | // left: None, 39 | // right: None 40 | // } 41 | // } 42 | // } 43 | use std::cell::RefCell; 44 | use std::i64::MAX; 45 | use std::i64::MIN; 46 | use std::rc::Rc; 47 | 48 | impl Solution { 49 | pub fn is_valid_bst(root: Option>>) -> bool { 50 | if root.is_none() { 51 | return true; 52 | } 53 | 54 | check(root, MAX, MIN) 55 | } 56 | } 57 | fn check(mut root: Option>>, upper: i64, lower: i64) -> bool { 58 | if root.is_none() { 59 | return true; 60 | } 61 | let val = root.as_ref().unwrap().borrow().val; 62 | let right = root.as_ref().unwrap().borrow_mut().right.take(); 63 | let left = root.as_ref().unwrap().borrow_mut().left.take(); 64 | if val as i64 <= lower || val as i64 >= upper { 65 | return false; 66 | } 67 | return check(left, val as i64, lower) && check(right, upper, val as i64); 68 | } 69 | // @lc code=end 70 | -------------------------------------------------------------------------------- /tree/medium/level_order/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/medium/level_order/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/level_order/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | // 输入: [1,null,2,3] 20 | // 1 21 | // \ 22 | // 2 23 | // / 24 | // 3 25 | 26 | // 输出: [1,3,2] 27 | use std::cell::RefCell; 28 | use std::collections::VecDeque; 29 | use std::rc::Rc; 30 | 31 | pub fn level_order(mut root: Option>>) -> Vec> { 32 | let mut v = vec![]; 33 | if root.is_none() { 34 | return v; 35 | } 36 | let mut queue = VecDeque::new(); 37 | queue.push_front(root); 38 | while queue.len() != 0 { 39 | let mut node_vec = vec![]; 40 | let mut val_vec = vec![]; 41 | while queue.len() != 0 { 42 | let node = queue.pop_front().unwrap().unwrap(); 43 | val_vec.push(node.borrow().val); // 记录当前行的所有元素的val 44 | node_vec.push(node); // 将当前队列中的所有元素出队并保存,即当前行的所有元素 45 | } 46 | v.push(val_vec); 47 | for i in &node_vec { 48 | // 把当前行所有元素的下一行元素入队 49 | let mut node = i; 50 | if !node.borrow().left.is_none() { 51 | queue.push_back(node.borrow_mut().left.take()); 52 | } 53 | if !node.borrow().right.is_none() { 54 | queue.push_back(node.borrow_mut().right.take()); 55 | } 56 | } 57 | } 58 | v 59 | } 60 | -------------------------------------------------------------------------------- /tree/medium/level_order/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /tree/medium/longest_univalue_path/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /tree/medium/longest_univalue_path/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/lowest_common_ancestor/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /tree/medium/lowest_common_ancestor/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/num_trees/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /tree/medium/num_trees/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/num_trees/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=96 lang=rust 3 | * 4 | * [96] 不同的二叉搜索树 5 | */ 6 | struct Solution {} 7 | // @lc code=start 8 | impl Solution { 9 | pub fn num_trees(n: i32) -> i32 { 10 | // 题解https://leetcode-cn.com/problems/unique-binary-search-trees/solution/bu-tong-de-er-cha-sou-suo-shu-by-leetcode-solution/ 11 | let mut dp = vec![0; (n + 1) as usize]; 12 | dp[0] = 1; 13 | dp[1] = 1; 14 | for i in 2..=n { 15 | for j in 1..=i { 16 | let i = i as usize; 17 | let j = j as usize; 18 | dp[i] += dp[j - 1] * dp[i - j]; 19 | } 20 | } 21 | println!("{:?}", dp); 22 | dp[n as usize] 23 | } 24 | } 25 | // @lc code=end 26 | #[cfg(test)] 27 | mod tests { 28 | use super::*; 29 | 30 | #[test] 31 | fn tests() { 32 | Solution::num_trees(3); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /tree/medium/preorder_traversal/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /tree/medium/preorder_traversal/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /tree/medium/preorder_traversal/src/lib.rs: -------------------------------------------------------------------------------- 1 | //Definition for a binary tree node. 2 | #[derive(Debug, PartialEq, Eq)] 3 | pub struct TreeNode { 4 | pub val: i32, 5 | pub left: Option>>, 6 | pub right: Option>>, 7 | } 8 | 9 | impl TreeNode { 10 | #[inline] 11 | pub fn new(val: i32) -> Self { 12 | TreeNode { 13 | val, 14 | left: None, 15 | right: None, 16 | } 17 | } 18 | } 19 | // 输入: [1,null,2,3] 20 | // 1 21 | // \ 22 | // 2 23 | // / 24 | // 3 25 | 26 | // 输出: [1,2,3] 27 | use std::cell::RefCell; 28 | use std::rc::Rc; 29 | 30 | pub fn preorder_traversal(mut root: Option>>) -> Vec { 31 | let mut v = vec![]; 32 | if root.is_none() { 33 | return v; 34 | } 35 | let mut stack = vec![]; 36 | while stack.len() != 0 || !root.is_none() { 37 | while !root.is_none() { 38 | // 一直添加左子树直到为空 39 | let node = root.unwrap(); 40 | v.push(node.borrow().val); 41 | root = node.borrow_mut().left.take(); 42 | stack.push(node); 43 | } 44 | // 从栈中弹出,取节点的右子树 45 | root = stack.pop(); 46 | root = root.unwrap().borrow_mut().right.take(); 47 | } 48 | v 49 | } 50 | -------------------------------------------------------------------------------- /tree/medium/preorder_traversal/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() {} 2 | -------------------------------------------------------------------------------- /tree/medium/zigzag_level_order/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /tree/medium/zigzag_level_order/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /weekly-test/2020-08-09/can_convert_string/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /weekly-test/2020-08-09/can_convert_string/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /weekly-test/2020-08-09/can_convert_string/src/lib.rs: -------------------------------------------------------------------------------- 1 | struct Solution {} 2 | 3 | use std::cmp::max; 4 | use std::collections::HashMap; 5 | 6 | impl Solution { 7 | pub fn can_convert_string(s: String, t: String, k: i32) -> bool { 8 | if s.len() != t.len() { 9 | return false; 10 | } 11 | let s_arr: Vec<&str> = s.split("").collect(); // string转vector 12 | let mut s_arr_new = vec![]; 13 | for i in 1..s_arr.len() - 1 { 14 | let item = s_arr[i]; 15 | s_arr_new.push(item.bytes().next().unwrap()) 16 | } 17 | 18 | let sign_arr: Vec<&str> = t.split("").collect(); 19 | let mut i = 1; 20 | let mut sign_arr_new = vec![]; 21 | while i < sign_arr.len() - 1 { 22 | let item = sign_arr[i]; 23 | 24 | if item.bytes().next().unwrap() >= s_arr_new[i - 1] { 25 | sign_arr_new.push(item.bytes().next().unwrap() - s_arr_new[i - 1]) 26 | } else { 27 | sign_arr_new.push(26 - (s_arr_new[i - 1] - item.bytes().next().unwrap())) 28 | } 29 | i += 1; 30 | } 31 | println!("{:?}", sign_arr_new); 32 | 33 | let mut hash_map: HashMap = HashMap::new(); 34 | let mut res: i32 = 0; 35 | for item in sign_arr_new { 36 | if item != 0 { 37 | let get_item = hash_map.get_mut(&item); 38 | if get_item.is_none() { 39 | hash_map.insert(item, 1); 40 | res = max(res, item as i32); 41 | } else { 42 | let get_item_val = get_item.unwrap().clone(); 43 | let item_new = item as i32 + 26 * get_item_val; 44 | hash_map.insert(item, get_item_val + 1); 45 | res = max(res as i32, item_new); 46 | } 47 | } 48 | } 49 | println!("{:?}", res); 50 | return res <= k; 51 | } 52 | } 53 | 54 | #[cfg(test)] 55 | mod tests { 56 | use super::*; 57 | 58 | #[test] 59 | fn tests() { 60 | Solution::can_convert_string("input".to_string(), "ouput".to_string(), 10); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /weekly-test/2020-08-09/find_kth_positive/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "leetcodebyrust" 5 | version = "0.1.0" 6 | -------------------------------------------------------------------------------- /weekly-test/2020-08-09/find_kth_positive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcodebyrust" 3 | version = "0.1.0" 4 | authors = ["zhangyuang "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | --------------------------------------------------------------------------------