From ed07425a78bde1b967da6a2ade5c11145332494d Mon Sep 17 00:00:00 2001 From: Yuchen Xie Date: Wed, 16 Oct 2019 09:10:40 +0800 Subject: [PATCH] Fix the inconsistency between src/lib.rs and new problem-solving files, and rustfmt everything --- src/lib.rs | 10 +- src/main.rs | 57 +++-- src/n0001_two_sum.rs | 6 +- src/n0002_add_two_numbers.rs | 57 +++-- src/n0003_longest_substring.rs | 16 +- src/n0004_median_of_two_sorted_arrays.rs | 34 +-- src/n0005_longest_palindromic_substring.rs | 35 ++- src/n0006_zigzag_conversion.rs | 42 ++-- src/n0007_reverse_integer.rs | 30 +-- src/n0008_string_to_integer_atoi.rs | 83 +++--- src/n0009_palindrome_number.rs | 44 ++-- src/n0010_regular_expression_matching.rs | 61 +++-- src/n0011_container_with_most_water.rs | 36 ++- src/n0012_integer_to_roman.rs | 57 +++-- src/n0013_roman_to_integer.rs | 60 ++--- src/n0014_longest_common_prefix.rs | 57 +++-- src/n0015_3sum.rs | 84 +++++-- src/n0016_3sum_closest.rs | 33 ++- ...7_letter_combinations_of_a_phone_number.rs | 39 +-- src/n0018_4sum.rs | 48 ++-- src/n0019_remove_nth_node_from_end_of_list.rs | 36 ++- src/n0020_valid_parentheses.rs | 60 ++--- src/n0021_merge_two_sorted_lists.rs | 36 +-- src/n0022_generate_parentheses.rs | 33 ++- src/n0023_merge_k_sorted_lists.rs | 43 ++-- src/n0024_swap_nodes_in_pairs.rs | 34 ++- src/n0025_reverse_nodes_in_k_group.rs | 67 +++-- ...026_remove_duplicates_from_sorted_array.rs | 48 ++-- src/n0027_remove_element.rs | 66 ++--- src/n0028_implement_strstr.rs | 30 +-- src/n0029_divide_two_integers.rs | 29 ++- ...bstring_with_concatenation_of_all_words.rs | 104 +++++--- src/n0031_next_permutation.rs | 20 +- src/n0032_longest_valid_parentheses.rs | 38 ++- ...ast_position_of_element_in_sorted_array.rs | 21 +- src/n0035_search_insert_position.rs | 39 ++- src/n0036_valid_sudoku.rs | 134 ++++++---- src/n0037_sudoku_solver.rs | 27 +- src/n0038_count_and_say.rs | 30 +-- src/n0039_combination_sum.rs | 68 ++--- src/n0041_first_missing_positive.rs | 57 +++-- src/n0042_trapping_rain_water.rs | 13 +- src/n0043_multiply_strings.rs | 33 ++- src/n0044_wildcard_matching.rs | 61 +++-- src/n0045_jump_game_ii.rs | 19 +- src/n0046_permutations.rs | 47 ++-- src/n0047_permutations_ii.rs | 236 +++++++++--------- src/n0048_rotate_image.rs | 74 +++--- src/n0049_group_anagrams.rs | 30 +-- src/n0050_powx_n.rs | 34 +-- src/n0051_n_queens.rs | 63 ++--- src/n0052_n_queens_ii.rs | 34 +-- src/n0053_maximum_subarray.rs | 21 +- src/n0054_spiral_matrix.rs | 85 ++++--- src/n0055_jump_game.rs | 37 +-- src/n0056_merge_intervals.rs | 60 +++-- src/n0057_insert_interval.rs | 81 +++--- src/n0058_length_of_last_word.rs | 12 +- src/n0059_spiral_matrix_ii.rs | 59 +++-- src/n0060_permutation_sequence.rs | 39 ++- src/n0061_rotate_list.rs | 21 +- src/n0062_unique_paths.rs | 31 +-- src/n0063_unique_paths_ii.rs | 95 ++++--- src/n0064_minimum_path_sum.rs | 46 ++-- src/n0065_valid_number.rs | 19 +- src/n0066_plus_one.rs | 33 +-- src/n0067_add_binary.rs | 41 +-- src/n0068_text_justification.rs | 92 ++++--- src/n0069_sqrtx.rs | 24 +- src/n0070_climbing_stairs.rs | 30 ++- src/n0071_simplify_path.rs | 84 ++++--- src/n0072_edit_distance.rs | 29 ++- src/n0073_set_matrix_zeroes.rs | 95 ++++--- src/n0074_search_a_2d_matrix.rs | 52 ++-- src/n0075_sort_colors.rs | 46 ++-- src/n0076_minimum_window_substring.rs | 29 +-- src/n0077_combinations.rs | 42 ++-- src/n0078_subsets.rs | 31 +-- src/n0079_word_search.rs | 104 +++++--- ..._remove_duplicates_from_sorted_array_ii.rs | 45 ++-- ...n0081_search_in_rotated_sorted_array_ii.rs | 31 ++- ...2_remove_duplicates_from_sorted_list_ii.rs | 25 +- ...0083_remove_duplicates_from_sorted_list.rs | 25 +- src/n0084_largest_rectangle_in_histogram.rs | 54 ++-- src/n0085_maximal_rectangle.rs | 15 +- src/n0086_partition_list.rs | 27 +- src/n0087_scramble_string.rs | 51 ++-- src/n0088_merge_sorted_array.rs | 45 ++-- src/n0089_gray_code.rs | 30 +-- src/n0090_subsets_ii.rs | 66 +++-- src/n0091_decode_ways.rs | 27 +- src/n0092_reverse_linked_list_ii.rs | 19 +- src/n0093_restore_ip_addresses.rs | 13 +- src/n0094_binary_tree_inorder_traversal.rs | 26 +- src/n0095_unique_binary_search_trees_ii.rs | 23 +- src/n0096_unique_binary_search_trees.rs | 15 +- src/n0097_interleaving_string.rs | 104 +++++--- src/n0098_validate_binary_search_tree.rs | 57 +++-- src/n0099_recover_binary_search_tree.rs | 88 ++++--- src/n0100_same_tree.rs | 54 ++-- src/n0101_symmetric_tree.rs | 58 +++-- ...n0102_binary_tree_level_order_traversal.rs | 42 ++-- ...inary_tree_zigzag_level_order_traversal.rs | 34 ++- src/n0104_maximum_depth_of_binary_tree.rs | 22 +- ...ree_from_preorder_and_inorder_traversal.rs | 40 +-- ...07_binary_tree_level_order_traversal_ii.rs | 42 ++-- ...vert_sorted_array_to_binary_search_tree.rs | 35 +-- ...nvert_sorted_list_to_binary_search_tree.rs | 37 +-- src/n0110_balanced_binary_tree.rs | 47 ++-- src/n0111_minimum_depth_of_binary_tree.rs | 32 +-- src/n0112_path_sum.rs | 44 ++-- src/n0113_path_sum_ii.rs | 45 ++-- ...0114_flatten_binary_tree_to_linked_list.rs | 34 +-- src/n0115_distinct_subsequences.rs | 76 +++--- src/n0118_pascals_triangle.rs | 31 +-- src/n0119_pascals_triangle_ii.rs | 39 ++- src/n0120_triangle.rs | 27 +- src/n0121_best_time_to_buy_and_sell_stock.rs | 28 +-- ...0122_best_time_to_buy_and_sell_stock_ii.rs | 36 +-- ...123_best_time_to_buy_and_sell_stock_iii.rs | 76 +++--- src/n0124_binary_tree_maximum_path_sum.rs | 67 ++--- src/n0125_valid_palindrome.rs | 46 ++-- src/n0126_word_ladder_ii.rs | 178 +++++++++---- src/n0127_word_ladder.rs | 62 +++-- src/n0128_longest_consecutive_sequence.rs | 37 +-- src/n0129_sum_root_to_leaf_numbers.rs | 34 +-- src/n0130_surrounded_regions.rs | 192 ++++++++------ src/n0131_palindrome_partitioning.rs | 80 +++--- src/n0132_palindrome_partitioning_ii.rs | 48 ++-- src/n0134_gas_station.rs | 45 ++-- src/n0135_candy.rs | 44 ++-- src/n0139_word_break.rs | 63 +++-- src/n0140_word_break_ii.rs | 35 ++- src/n0143_reorder_list.rs | 31 ++- src/n0144_binary_tree_preorder_traversal.rs | 23 +- src/n0145_binary_tree_postorder_traversal.rs | 23 +- src/n0146_lru_cache.rs | 58 +++-- src/n0147_insertion_sort_list.rs | 33 ++- src/n0148_sort_list.rs | 79 +++--- src/n0149_max_points_on_a_line.rs | 109 +++++--- src/n0150_evaluate_reverse_polish_notation.rs | 52 ++-- src/n0151_reverse_words_in_a_string.rs | 52 ++-- src/n0152_maximum_product_subarray.rs | 51 ++-- ...53_find_minimum_in_rotated_sorted_array.rs | 34 +-- ...find_minimum_in_rotated_sorted_array_ii.rs | 46 ++-- src/n0155_min_stack.rs | 59 +++-- src/n0162_find_peak_element.rs | 36 +-- src/n0164_maximum_gap.rs | 36 +-- src/n0165_compare_version_numbers.rs | 56 +++-- src/n0166_fraction_to_recurring_decimal.rs | 29 ++- src/n0167_two_sum_ii_input_array_is_sorted.rs | 22 +- src/n0168_excel_sheet_column_title.rs | 39 +-- src/n0169_majority_element.rs | 44 ++-- src/n0171_excel_sheet_column_number.rs | 37 ++- src/n0172_factorial_trailing_zeroes.rs | 16 +- src/n0173_binary_search_tree_iterator.rs | 64 +++-- src/n0174_dungeon_game.rs | 72 +++--- src/n0179_largest_number.rs | 41 +-- src/n0187_repeated_dna_sequences.rs | 62 ++--- ...0188_best_time_to_buy_and_sell_stock_iv.rs | 76 +++--- src/n0189_rotate_array.rs | 34 +-- src/n0198_house_robber.rs | 36 +-- src/n0199_binary_tree_right_side_view.rs | 28 ++- src/n0200_number_of_islands.rs | 64 +++-- src/n0201_bitwise_and_of_numbers_range.rs | 18 +- src/n0202_happy_number.rs | 20 +- src/n0203_remove_linked_list_elements.rs | 17 +- src/n0204_count_primes.rs | 21 +- src/n0205_isomorphic_strings.rs | 49 ++-- src/n0206_reverse_linked_list.rs | 7 +- src/n0209_minimum_size_subarray_sum.rs | 15 +- src/n0210_course_schedule_ii.rs | 11 +- ...d_and_search_word_data_structure_design.rs | 2 - src/n0213_house_robber_ii.rs | 8 +- src/n0215_kth_largest_element_in_an_array.rs | 13 +- src/n0216_combination_sum_iii.rs | 17 +- src/n0217_contains_duplicate.rs | 10 +- src/n0219_contains_duplicate_ii.rs | 16 +- src/n0220_contains_duplicate_iii.rs | 23 +- src/n0221_maximal_square.rs | 49 ++-- src/n0222_count_complete_tree_nodes.rs | 16 +- src/n0223_rectangle_area.rs | 18 +- src/n0224_basic_calculator.rs | 38 +-- src/n0225_implement_stack_using_queues.rs | 6 +- src/n0226_invert_binary_tree.rs | 5 +- src/n0227_basic_calculator_ii.rs | 16 +- src/n0228_summary_ranges.rs | 9 +- src/n0229_majority_element_ii.rs | 18 +- src/n0230_kth_smallest_element_in_a_bst.rs | 8 +- src/n0232_implement_queue_using_stacks.rs | 6 +- src/n0238_product_of_array_except_self.rs | 15 +- src/n0239_sliding_window_maximum.rs | 19 +- ...n0241_different_ways_to_add_parentheses.rs | 13 +- src/n0242_valid_anagram.rs | 7 +- src/n0257_binary_tree_paths.rs | 5 +- src/n0260_single_number_iii.rs | 4 +- src/n0263_ugly_number.rs | 6 +- src/n0264_ugly_number_ii.rs | 14 +- src/n0268_missing_number.rs | 4 +- src/n0274_h_index.rs | 2 +- src/n0275_h_index_ii.rs | 12 +- src/n0279_perfect_squares.rs | 8 +- src/n0283_move_zeroes.rs | 4 +- src/n0287_find_the_duplicate_number.rs | 8 +- src/n0289_game_of_life.rs | 39 +-- src/n0290_word_pattern.rs | 22 +- src/n0295_find_median_from_data_stream.rs | 12 +- src/n0299_bulls_and_cows.rs | 10 +- src/n0300_longest_increasing_subsequence.rs | 2 +- src/n0301_remove_invalid_parentheses.rs | 48 +++- src/n0303_range_sum_query_immutable.rs | 4 +- src/n0304_range_sum_query_2d_immutable.rs | 58 +++-- src/n0306_additive_number.rs | 31 ++- src/n0307_range_sum_query_mutable.rs | 46 ++-- ...ime_to_buy_and_sell_stock_with_cooldown.rs | 28 +-- src/n0310_minimum_height_trees.rs | 13 +- src/n0312_burst_balloons.rs | 55 ++-- src/n0313_super_ugly_number.rs | 22 +- src/n1009_pancake_sorting.rs | 63 +++-- src/n1071_binary_prefix_divisible_by_5.rs | 3 +- src/n1127_last_stone_weight.rs | 2 +- src/problem.rs | 27 +- src/util/linked_list.rs | 7 +- src/util/mod.rs | 2 +- src/util/point.rs | 5 +- src/util/testing.rs | 1 + src/util/tree.rs | 5 +- 227 files changed, 5041 insertions(+), 3950 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index a3401abf..7278e7b0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -186,11 +186,11 @@ mod n0215_kth_largest_element_in_an_array; mod n0216_combination_sum_iii; mod n0217_contains_duplicate; mod n0218_the_skyline_problem; -mod n0220_contains_duplicate_iii; mod n0219_contains_duplicate_ii; +mod n0220_contains_duplicate_iii; mod n0221_maximal_square; -mod n0223_rectangle_area; mod n0222_count_complete_tree_nodes; +mod n0223_rectangle_area; mod n0224_basic_calculator; mod n0225_implement_stack_using_queues; mod n0226_invert_binary_tree; @@ -227,12 +227,14 @@ mod n0300_longest_increasing_subsequence; mod n0301_remove_invalid_parentheses; mod n0303_range_sum_query_immutable; mod n0304_range_sum_query_2d_immutable; -mod n1009_pancake_sorting; mod n0306_additive_number; mod n0307_range_sum_query_mutable; mod n0309_best_time_to_buy_and_sell_stock_with_cooldown; mod n0310_minimum_height_trees; mod n0312_burst_balloons; mod n0313_super_ugly_number; -mod n1013_fibonacci_number; mod n0792_binary_search; +mod n1009_pancake_sorting; +mod n1013_fibonacci_number; +mod n1071_binary_prefix_divisible_by_5; +mod n1127_last_stone_weight; diff --git a/src/main.rs b/src/main.rs index bfb42698..b914f2d9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,20 +7,21 @@ mod problem; use std::env; use std::fs; -use std::path::{Path}; -use std::io::Write; use std::io; +use std::io::Write; +use std::path::Path; /// main() helps to generate the submission template .rs fn main() { println!("Welcome to leetcode-rust system."); let mut solved_ids = get_solved_ids(); loop { - println!("Please enter a problem id, or enter \"random\" to generate a random problem."); + println!("Please enter a frontend problem id, or \"random\" to generate a random one."); let mut is_random = false; - let mut id :u32 = 0; + let mut id: u32 = 0; let mut id_arg = String::new(); - io::stdin().read_line(&mut id_arg) + io::stdin() + .read_line(&mut id_arg) .expect("Failed to read line"); let id_arg = id_arg.trim(); match id_arg { @@ -29,23 +30,30 @@ fn main() { id = generate_random_id(&solved_ids); is_random = true; println!("Generate random problem: {}", &id); - }, + } _ => { - id = id_arg.parse::().expect(&format!("not a number: {}", id_arg)); + id = id_arg + .parse::() + .expect(&format!("not a number: {}", id_arg)); if solved_ids.contains(&id) { - println!("The problem you chose is invalid (the problem may have been solved \ - or may have no rust version)."); + println!( + "The problem you chose is invalid (the problem may have been solved \ + or may have no rust version)." + ); continue; } } } - let problem = problem::get_problem(id) - .expect(&format!("Error: failed to get problem #{} \ - (The problem may be paid-only or may not be exist).", - id)); - let code = problem.code_definition.iter() - .filter(|&d| { d.value == "rust" }) + let problem = problem::get_problem(id).expect(&format!( + "Error: failed to get problem #{} \ + (The problem may be paid-only or may not be exist).", + id + )); + let code = problem + .code_definition + .iter() + .filter(|&d| d.value == "rust") .next(); if code.is_none() { println!("Problem {} has no rust version.", &id); @@ -54,7 +62,11 @@ fn main() { } let code = code.unwrap(); - let file_name = format!("n{:04}_{}", problem.question_id, problem.title_slug.replace("-", "_")); + let file_name = format!( + "n{:04}_{}", + problem.question_id, + problem.title_slug.replace("-", "_") + ); let file_path = Path::new("./src").join(format!("{}.rs", file_name)); if file_path.exists() { panic!("problem already initialized"); @@ -88,17 +100,20 @@ fn main() { } } -fn generate_random_id(except_ids : &Vec) -> u32 { - use std::fs; +fn generate_random_id(except_ids: &Vec) -> u32 { use rand::Rng; + use std::fs; let mut rng = rand::thread_rng(); loop { - let res :u32 = rng.gen_range(1, 1106); + let res: u32 = rng.gen_range(1, 1106); if !except_ids.contains(&res) { return res; } - println!("Generate a random num ({}), but it is invalid (the problem may have been solved \ - or may have no rust version). Regenerate..", res); + println!( + "Generate a random num ({}), but it is invalid (the problem may have been solved \ + or may have no rust version). Regenerate..", + res + ); } } diff --git a/src/n0001_two_sum.rs b/src/n0001_two_sum.rs index 92e23909..1d04a13e 100644 --- a/src/n0001_two_sum.rs +++ b/src/n0001_two_sum.rs @@ -26,8 +26,10 @@ impl Solution { let mut map = HashMap::with_capacity(nums.len()); for (index, num) in nums.iter().enumerate() { match map.get(&(target - num)) { - None => { map.insert(num, index); }, - Some(sub_index) => { return vec![*sub_index as i32, index as i32] }, + None => { + map.insert(num, index); + } + Some(sub_index) => return vec![*sub_index as i32, index as i32], } } vec![] diff --git a/src/n0002_add_two_numbers.rs b/src/n0002_add_two_numbers.rs index bb0b0da4..b7b21b01 100644 --- a/src/n0002_add_two_numbers.rs +++ b/src/n0002_add_two_numbers.rs @@ -4,10 +4,10 @@ * You are given two non-empty linked lists representing two non-negative * integers. The digits are stored in reverse order and each of their nodes * contain a single digit. Add the two numbers and return it as a linked list. - * + * * You may assume the two numbers do not contain any leading zero, except the * number 0 itself. - * + * * Example: * * @@ -17,31 +17,52 @@ * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here impl Solution { - pub fn add_two_numbers(l1: Option>, l2: Option>) -> Option> { + pub fn add_two_numbers( + l1: Option>, + l2: Option>, + ) -> Option> { let (mut l1, mut l2) = (l1, l2); let mut dummy_head = Some(Box::new(ListNode::new(0))); let mut tail = &mut dummy_head; let (mut l1_end, mut l2_end, mut overflow) = (false, false, false); loop { let lhs = match l1 { - Some(node) => { l1 = node.next; node.val }, - None => { l1_end = true; 0 }, + Some(node) => { + l1 = node.next; + node.val + } + None => { + l1_end = true; + 0 + } }; let rhs = match l2 { - Some(node) => { l2 = node.next; node.val }, - None => { l2_end = true; 0 } + Some(node) => { + l2 = node.next; + node.val + } + None => { + l2_end = true; + 0 + } }; // if l1, l2 end and there is not overflow from previous operation, return the result if l1_end && l2_end && !overflow { - break dummy_head.unwrap().next + break dummy_head.unwrap().next; } let sum = lhs + rhs + if overflow { 1 } else { 0 }; - let sum = if sum >= 10 { overflow = true; sum - 10 } else { overflow = false; sum }; + let sum = if sum >= 10 { + overflow = true; + sum - 10 + } else { + overflow = false; + sum + }; tail.as_mut().unwrap().next = Some(Box::new(ListNode::new(sum))); tail = &mut tail.as_mut().unwrap().next } @@ -50,17 +71,25 @@ impl Solution { // submission codes end - #[cfg(test)] mod tests { use super::*; #[test] fn test_2() { - assert_eq!(Solution::add_two_numbers(to_list(vec![2, 4, 3]), to_list(vec![5, 6, 4])), to_list(vec![7, 0, 8])); + assert_eq!( + Solution::add_two_numbers(to_list(vec![2, 4, 3]), to_list(vec![5, 6, 4])), + to_list(vec![7, 0, 8]) + ); - assert_eq!(Solution::add_two_numbers(to_list(vec![9, 9, 9, 9]), to_list(vec![9, 9, 9, 9, 9, 9])), to_list(vec![8, 9, 9, 9, 0, 0, 1])); + assert_eq!( + Solution::add_two_numbers(to_list(vec![9, 9, 9, 9]), to_list(vec![9, 9, 9, 9, 9, 9])), + to_list(vec![8, 9, 9, 9, 0, 0, 1]) + ); - assert_eq!(Solution::add_two_numbers(to_list(vec![0]), to_list(vec![0])), to_list(vec![0])) + assert_eq!( + Solution::add_two_numbers(to_list(vec![0]), to_list(vec![0])), + to_list(vec![0]) + ) } } diff --git a/src/n0003_longest_substring.rs b/src/n0003_longest_substring.rs index fc3366d1..dca33069 100644 --- a/src/n0003_longest_substring.rs +++ b/src/n0003_longest_substring.rs @@ -24,11 +24,13 @@ impl Solution { for idx in start..end { if seq[end] == seq[idx] { start = idx + 1; - break + break; } } let curr = end - start + 1; - if curr > max { max = curr } + if curr > max { + max = curr + } end += 1 } max as i32 @@ -43,8 +45,14 @@ mod tests { #[test] fn test_3() { - assert_eq!(Solution::length_of_longest_substring("abcabcbb".to_string()), 3); + assert_eq!( + Solution::length_of_longest_substring("abcabcbb".to_string()), + 3 + ); assert_eq!(Solution::length_of_longest_substring("bbbb".to_string()), 1); - assert_eq!(Solution::length_of_longest_substring("pwwkew".to_string()), 3); + assert_eq!( + Solution::length_of_longest_substring("pwwkew".to_string()), + 3 + ); } } diff --git a/src/n0004_median_of_two_sorted_arrays.rs b/src/n0004_median_of_two_sorted_arrays.rs index 96d51619..b0775e14 100644 --- a/src/n0004_median_of_two_sorted_arrays.rs +++ b/src/n0004_median_of_two_sorted_arrays.rs @@ -2,29 +2,29 @@ * [4] Median of Two Sorted Arrays * * There are two sorted arrays nums1 and nums2 of size m and n respectively. - * + * * Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). - * + * * You may assume nums1 and nums2 cannot be both empty. - * + * * Example 1: - * + * * * nums1 = [1, 3] * nums2 = [2] - * + * * The median is 2.0 - * - * + * + * * Example 2: - * - * + * + * * nums1 = [1, 2] * nums2 = [3, 4] - * + * * The median is (2 + 3)/2 = 2.5 - * - * + * + * */ pub struct Solution {} @@ -47,7 +47,13 @@ mod tests { #[test] #[ignore] fn test_4() { - assert_eq!(Solution::find_median_sorted_arrays(vec![1, 3], vec![2]), 2.0); - assert_eq!(Solution::find_median_sorted_arrays(vec![1, 2], vec![3, 4]), 2.5); + assert_eq!( + Solution::find_median_sorted_arrays(vec![1, 3], vec![2]), + 2.0 + ); + assert_eq!( + Solution::find_median_sorted_arrays(vec![1, 2], vec![3, 4]), + 2.5 + ); } } diff --git a/src/n0005_longest_palindromic_substring.rs b/src/n0005_longest_palindromic_substring.rs index f48ebd86..26a622ca 100644 --- a/src/n0005_longest_palindromic_substring.rs +++ b/src/n0005_longest_palindromic_substring.rs @@ -2,18 +2,18 @@ * [5] Longest Palindromic Substring * * Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. - * + * * Example 1: - * - * + * + * * Input: "babad" * Output: "bab" * Note: "aba" is also a valid answer. - * - * + * + * * Example 2: - * - * + * + * * Input: "cbbd" * Output: "bb" * @@ -27,28 +27,37 @@ impl Solution { pub fn longest_palindrome(s: String) -> String { let seq: Vec = s.chars().collect(); let len = seq.len(); - if len < 1 {return s} + if len < 1 { + return s; + } let (mut idx, mut curr_len, mut curr_start, mut curr_end) = (0, 0, 0, 0); while idx < len { let (mut i, mut j) = (idx, idx); let ch = seq[idx]; // handle same char - while i > 0 && seq[i - 1] == ch { i -= 1 }; - while j < len - 1 && seq[j + 1] == ch { j += 1 }; + while i > 0 && seq[i - 1] == ch { + i -= 1 + } + while j < len - 1 && seq[j + 1] == ch { + j += 1 + } idx = j + 1; while i > 0 && j < len - 1 && seq[i - 1] == seq[j + 1] { - i -= 1; j +=1; + i -= 1; + j += 1; } let max_len = j - i + 1; if max_len > curr_len { - curr_len = max_len; curr_start = i; curr_end = j; + curr_len = max_len; + curr_start = i; + curr_end = j; } if max_len >= len - 1 { break; } } - s[curr_start..curr_end+1].to_owned() + s[curr_start..curr_end + 1].to_owned() } } diff --git a/src/n0006_zigzag_conversion.rs b/src/n0006_zigzag_conversion.rs index 30d90490..43bf5fdc 100644 --- a/src/n0006_zigzag_conversion.rs +++ b/src/n0006_zigzag_conversion.rs @@ -2,39 +2,39 @@ * [6] ZigZag Conversion * * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) - * - * + * + * * P A H N * A P L S I I G * Y I R - * - * + * + * * And then read line by line: "PAHNAPLSIIGYIR" - * + * * Write the code that will take a string and make this conversion given a number of rows: - * - * + * + * * string convert(string s, int numRows); - * + * * Example 1: - * - * + * + * * Input: s = "PAYPALISHIRING", numRows = 3 * Output: "PAHNAPLSIIGYIR" - * - * + * + * * Example 2: - * - * + * + * * Input: s = "PAYPALISHIRING", numRows = 4 * Output: "PINALSIGYAHRPI" * Explanation: - * + * * P I N * A L S I G * Y A H R * P I - * + * */ pub struct Solution {} @@ -78,8 +78,14 @@ mod tests { #[test] fn test_6() { - assert_eq!(Solution::convert("PAYPALISHIRING".to_string(), 4), "PINALSIGYAHRPI"); - assert_eq!(Solution::convert("PAYPALISHIRING".to_string(), 3), "PAHNAPLSIIGYIR"); + assert_eq!( + Solution::convert("PAYPALISHIRING".to_string(), 4), + "PINALSIGYAHRPI" + ); + assert_eq!( + Solution::convert("PAYPALISHIRING".to_string(), 3), + "PAHNAPLSIIGYIR" + ); assert_eq!(Solution::convert("A".to_string(), 1), "A"); assert_eq!(Solution::convert("AY".to_string(), 2), "AY"); } diff --git a/src/n0007_reverse_integer.rs b/src/n0007_reverse_integer.rs index 9810cf5a..d258809f 100644 --- a/src/n0007_reverse_integer.rs +++ b/src/n0007_reverse_integer.rs @@ -2,31 +2,31 @@ * [7] Reverse Integer * * Given a 32-bit signed integer, reverse digits of an integer. - * + * * Example 1: - * - * + * + * * Input: 123 * Output: 321 - * - * + * + * * Example 2: - * - * + * + * * Input: -123 * Output: -321 - * - * + * + * * Example 3: - * - * + * + * * Input: 120 * Output: 21 - * - * + * + * * Note:
* Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31, 2^31 - 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. - * + * */ pub struct Solution {} @@ -38,7 +38,7 @@ impl Solution { let mut digit: i64 = 0; let base: i64 = 2; let upper_bound: i64 = base.pow(31) - 1; - let lower_bound: i64 = - base.pow(31); + let lower_bound: i64 = -base.pow(31); while input != 0 { digit = input % 10; result = result * 10 + digit; diff --git a/src/n0008_string_to_integer_atoi.rs b/src/n0008_string_to_integer_atoi.rs index 5eef8f01..15a1eae1 100644 --- a/src/n0008_string_to_integer_atoi.rs +++ b/src/n0008_string_to_integer_atoi.rs @@ -2,62 +2,62 @@ * [8] String to Integer (atoi) * * Implement atoi which converts a string to an integer. - * + * * The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. - * + * * The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. - * + * * If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. - * + * * If no valid conversion could be performed, a zero value is returned. - * + * * Note: - * + * *
    *
  • Only the space character ' ' is considered as whitespace character.
  • *
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31, 2^31 - 1]. If the numerical value is out of the range of representable values, INT_MAX (2^31 - 1) or INT_MIN (-2^31) is returned.
  • *
- * + * * Example 1: - * - * + * + * * Input: "42" * Output: 42 - * - * + * + * * Example 2: - * - * + * + * * Input: " -42" * Output: -42 * Explanation: The first non-whitespace character is '-', which is the minus sign. * Then take as many numerical digits as possible, which gets 42. - * - * + * + * * Example 3: - * - * + * + * * Input: "4193 with words" * Output: 4193 * Explanation: Conversion stops at digit '3' as the next character is not a numerical digit. - * - * + * + * * Example 4: - * - * + * + * * Input: "words and 987" * Output: 0 - * Explanation: The first non-whitespace character is 'w', which is not a numerical + * Explanation: The first non-whitespace character is 'w', which is not a numerical * digit or a +/- sign. Therefore no valid conversion could be performed. - * + * * Example 5: - * - * + * + * * Input: "-91283472332" * Output: -2147483648 * Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. * Thefore INT_MIN (-2^31) is returned. - * + * */ pub struct Solution {} @@ -73,28 +73,39 @@ impl Solution { for ch in input.chars().into_iter() { if !num_matched { match ch { - ' ' => {}, + ' ' => {} '0'..='9' => { num_matched = true; result = result * 10 + ch.to_digit(10).unwrap() as i64; - }, - '-' => { num_matched = true; minus = true; } - '+' => { num_matched = true; } - _ => return 0 + } + '-' => { + num_matched = true; + minus = true; + } + '+' => { + num_matched = true; + } + _ => return 0, } } else { match ch { '0'..='9' => { result = result * 10 + ch.to_digit(10).unwrap() as i64; - if result > i32_max { break } - }, - _ => break + if result > i32_max { + break; + } + } + _ => break, } } } result = if minus { -result } else { result }; - if result > i32_max { return i32_max as i32; } - if result < i32_min { return i32_min as i32; } + if result > i32_max { + return i32_max as i32; + } + if result < i32_min { + return i32_min as i32; + } return result as i32; } } diff --git a/src/n0009_palindrome_number.rs b/src/n0009_palindrome_number.rs index 7f85c1e6..070077a3 100644 --- a/src/n0009_palindrome_number.rs +++ b/src/n0009_palindrome_number.rs @@ -2,34 +2,34 @@ * [9] Palindrome Number * * Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. - * + * * Example 1: - * - * + * + * * Input: 121 * Output: true - * - * + * + * * Example 2: - * - * + * + * * Input: -121 * Output: false * Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. - * - * + * + * * Example 3: - * - * + * + * * Input: 10 * Output: false * Explanation: Reads 01 from right to left. Therefore it is not a palindrome. - * - * + * + * * Follow up: - * + * * Coud you solve it without converting the integer to a string? - * + * */ pub struct Solution {} @@ -38,7 +38,9 @@ pub struct Solution {} // TODO: not optimal, we only have to revert half of the string impl Solution { pub fn is_palindrome(x: i32) -> bool { - if x < 0 { return false } + if x < 0 { + return false; + } let mut digits: Vec = Vec::new(); let mut input = x; while input != 0 { @@ -47,13 +49,17 @@ impl Solution { } let len = digits.len(); // handle one digit - if len < 2 { return true } + if len < 2 { + return true; + } // handle end with 0 - if digits[0] == 0 { return false } + if digits[0] == 0 { + return false; + } let mut i = 0; while i < len / 2 { if digits[i] != digits[len - 1 - i] { - return false + return false; } i += 1; } diff --git a/src/n0010_regular_expression_matching.rs b/src/n0010_regular_expression_matching.rs index 15607125..d600e619 100644 --- a/src/n0010_regular_expression_matching.rs +++ b/src/n0010_regular_expression_matching.rs @@ -2,70 +2,70 @@ * [10] Regular Expression Matching * * Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. - * - * + * + * * '.' Matches any single character. * '*' Matches zero or more of the preceding element. - * - * + * + * * The matching should cover the entire input string (not partial). - * + * * Note: - * - * + * + * * s could be empty and contains only lowercase letters a-z. * p could be empty and contains only lowercase letters a-z, and characters like . or *. - * - * + * + * * Example 1: - * - * + * + * * Input: * s = "aa" * p = "a" * Output: false * Explanation: "a" does not match the entire string "aa". - * - * + * + * * Example 2: - * - * + * + * * Input: * s = "aa" * p = "a*" * Output: true * Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". - * - * + * + * * Example 3: - * - * + * + * * Input: * s = "ab" * p = ".*" * Output: true * Explanation: ".*" means "zero or more (*) of any character (.)". - * - * + * + * * Example 4: - * - * + * + * * Input: * s = "aab" * p = "c*a*b" * Output: true * Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab". - * - * + * + * * Example 5: - * - * + * + * * Input: * s = "mississippi" * p = "mis*is*p*." * Output: false - * - * + * + * */ pub struct Solution {} @@ -85,6 +85,5 @@ mod tests { use super::*; #[test] - fn test_10() { - } + fn test_10() {} } diff --git a/src/n0011_container_with_most_water.rs b/src/n0011_container_with_most_water.rs index 8f7177dd..a26dcfb7 100644 --- a/src/n0011_container_with_most_water.rs +++ b/src/n0011_container_with_most_water.rs @@ -2,23 +2,23 @@ * [11] Container With Most Water * * Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. - * + * * Note: You may not slant the container and n is at least 2. - * + * * - * + * * - * + * * The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. - * + * * - * + * * Example: - * - * + * + * * Input: [1,8,6,2,5,4,8,3,7] * Output: 49 - * + * */ pub struct Solution {} @@ -36,20 +36,30 @@ impl Solution { // move the lower one if height[start] < height[end] { start += 1; - if height[start] < height[start - 1] { continue } + if height[start] < height[start - 1] { + continue; + } } else { end -= 1; - if height[end] < height[end + 1] { continue } + if height[end] < height[end + 1] { + continue; + } } curr_area = (end - start) as i32 * Solution::min(height[start], height[end]); - if curr_area > max { max = curr_area } + if curr_area > max { + max = curr_area + } } max } #[inline(always)] fn min(i: i32, j: i32) -> i32 { - if i > j { j } else { i } + if i > j { + j + } else { + i + } } } diff --git a/src/n0012_integer_to_roman.rs b/src/n0012_integer_to_roman.rs index 2c39e5b6..2698956e 100644 --- a/src/n0012_integer_to_roman.rs +++ b/src/n0012_integer_to_roman.rs @@ -2,8 +2,8 @@ * [12] Integer to Roman * * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. - * - * + * + * * Symbol Value * I 1 * V 5 @@ -12,59 +12,58 @@ * C 100 * D 500 * M 1000 - * + * * For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. - * + * * Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: - * - * - * I can be placed before V (5) and X (10) to make 4 and 9. - * X can be placed before L (50) and C (100) to make 40 and 90. + * + * + * I can be placed before V (5) and X (10) to make 4 and 9. + * X can be placed before L (50) and C (100) to make 40 and 90. * C can be placed before D (500) and M (1000) to make 400 and 900. - * - * + * + * * Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. - * + * * Example 1: - * - * + * + * * Input: 3 * Output: "III" - * + * * Example 2: - * - * + * + * * Input: 4 * Output: "IV" - * + * * Example 3: - * - * + * + * * Input: 9 * Output: "IX" - * + * * Example 4: - * - * + * + * * Input: 58 * Output: "LVIII" * Explanation: L = 50, V = 5, III = 3. - * - * + * + * * Example 5: - * - * + * + * * Input: 1994 * Output: "MCMXCIV" * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. - * + * */ pub struct Solution {} // submission codes start here impl Solution { - pub fn int_to_roman(num: i32) -> String { let table: Vec<(i32, &'static str)> = vec![ (1000, "M"), @@ -79,7 +78,7 @@ impl Solution { (9, "IX"), (5, "V"), (4, "IV"), - (1, "I") + (1, "I"), ]; let mut num = num; diff --git a/src/n0013_roman_to_integer.rs b/src/n0013_roman_to_integer.rs index 8566d1a9..fcc2c1ad 100644 --- a/src/n0013_roman_to_integer.rs +++ b/src/n0013_roman_to_integer.rs @@ -2,8 +2,8 @@ * [13] Roman to Integer * * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. - * - * + * + * * Symbol Value * I 1 * V 5 @@ -12,52 +12,52 @@ * C 100 * D 500 * M 1000 - * + * * For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. - * + * * Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: - * - * - * I can be placed before V (5) and X (10) to make 4 and 9. - * X can be placed before L (50) and C (100) to make 40 and 90. + * + * + * I can be placed before V (5) and X (10) to make 4 and 9. + * X can be placed before L (50) and C (100) to make 40 and 90. * C can be placed before D (500) and M (1000) to make 400 and 900. - * - * + * + * * Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. - * + * * Example 1: - * - * + * + * * Input: "III" * Output: 3 - * + * * Example 2: - * - * + * + * * Input: "IV" * Output: 4 - * + * * Example 3: - * - * + * + * * Input: "IX" * Output: 9 - * + * * Example 4: - * - * + * + * * Input: "LVIII" * Output: 58 * Explanation: L = 50, V= 5, III = 3. - * - * + * + * * Example 5: - * - * + * + * * Input: "MCMXCIV" * Output: 1994 * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. - * + * */ pub struct Solution {} @@ -78,16 +78,16 @@ impl Solution { (9, "IX"), (5, "V"), (4, "IV"), - (1, "I") + (1, "I"), ]; let mut sum = 0; let mut idx = 0; for p in table.iter() { - while idx+p.1.len() <= s.len() && p.1 == &s[idx..idx+p.1.len()] { + while idx + p.1.len() <= s.len() && p.1 == &s[idx..idx + p.1.len()] { idx += p.1.len(); sum += p.0; if idx >= s.len() { - return sum + return sum; } } } diff --git a/src/n0014_longest_common_prefix.rs b/src/n0014_longest_common_prefix.rs index 2cdd344f..3d3affec 100644 --- a/src/n0014_longest_common_prefix.rs +++ b/src/n0014_longest_common_prefix.rs @@ -1,30 +1,29 @@ - /** * [14] Longest Common Prefix * * Write a function to find the longest common prefix string amongst an array of strings. - * + * * If there is no common prefix, return an empty string "". - * + * * Example 1: - * - * + * + * * Input: ["flower","flow","flight"] * Output: "fl" - * - * + * + * * Example 2: - * - * + * + * * Input: ["dog","racecar","car"] * Output: "" * Explanation: There is no common prefix among the input strings. - * - * + * + * * Note: - * + * * All given inputs are in lowercase letters a-z. - * + * */ pub struct Solution {} @@ -34,21 +33,23 @@ use std::str::Chars; impl Solution { pub fn longest_common_prefix(strs: Vec) -> String { let mut prefix = String::new(); - let mut iters: Vec = strs.iter().map(|s| {s.chars()}).collect(); + let mut iters: Vec = strs.iter().map(|s| s.chars()).collect(); let mut curr_char: Option = None; - if strs.len() < 1 { return prefix } + if strs.len() < 1 { + return prefix; + } loop { curr_char.take().map(|ch| prefix.push(ch)); for iter in iters.iter_mut() { let mut ch = iter.next(); if ch.is_none() { - return prefix + return prefix; } match curr_char { None => curr_char = ch.take(), Some(curr) => { if curr != ch.unwrap() { - return prefix + return prefix; } } } @@ -65,12 +66,22 @@ mod tests { #[test] fn test_14() { - assert_eq!(Solution::longest_common_prefix(vec!["".to_string(), - "racecar".to_string(), - "car".to_string()]), ""); - assert_eq!(Solution::longest_common_prefix(vec!["flower".to_string(), - "flow".to_string(), - "flight".to_string()]), "fl"); + assert_eq!( + Solution::longest_common_prefix(vec![ + "".to_string(), + "racecar".to_string(), + "car".to_string() + ]), + "" + ); + assert_eq!( + Solution::longest_common_prefix(vec![ + "flower".to_string(), + "flow".to_string(), + "flight".to_string() + ]), + "fl" + ); assert_eq!(Solution::longest_common_prefix(vec![]), ""); } } diff --git a/src/n0015_3sum.rs b/src/n0015_3sum.rs index b62a1a21..2d4c9cca 100644 --- a/src/n0015_3sum.rs +++ b/src/n0015_3sum.rs @@ -2,23 +2,23 @@ * [15] 3Sum * * Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. - * + * * Note: - * + * * The solution set must not contain duplicate triplets. - * + * * Example: - * - * + * + * * Given array nums = [-1, 0, 1, 2, -1, -4], - * + * * A solution set is: * [ * [-1, 0, 1], * [-1, -1, 2] * ] - * - * + * + * */ pub struct Solution {} @@ -27,7 +27,9 @@ pub struct Solution {} impl Solution { pub fn three_sum(nums: Vec) -> Vec> { let len = nums.len(); - if len < 3 { return vec![] } + if len < 3 { + return vec![]; + } let mut nums = nums; nums.sort(); let mut i = 0; @@ -35,9 +37,12 @@ impl Solution { let mut previous = nums[0] - 1; while i < len - 2 { // skip same number - if nums[i] == previous { i += 1; continue } + if nums[i] == previous { + i += 1; + continue; + } previous = nums[i]; - let mut vec = Solution::two_sum(&nums[(i+1)..len], 0 - nums[i]); + let mut vec = Solution::two_sum(&nums[(i + 1)..len], 0 - nums[i]); for t in vec.iter() { result.push(vec![nums[i], t.0, t.1]); } @@ -52,9 +57,11 @@ impl Solution { let (mut i, mut j) = (0_usize, nums.len() - 1); let mut result = Vec::new(); while i < j { - if nums[i] + nums[j] < sum { i += 1 } - else if nums[i] + nums[j] > sum { j -= 1 } - else { + if nums[i] + nums[j] < sum { + i += 1 + } else if nums[i] + nums[j] > sum { + j -= 1 + } else { result.push((nums[i], nums[j])); i = Solution::next_unique(nums, i, true); j = Solution::next_unique(nums, j, false); @@ -83,13 +90,50 @@ mod tests { #[test] fn test_15() { - assert_eq!(Solution::three_sum(vec![-1, 0, 1, 2, -1, -4]), vec![vec![-1, -1, 2], vec![-1, 0, 1]]); - assert_eq!(Solution::three_sum( - vec![-7,-4,-6,6,4,-6,-9,-10,-7,5,3,-1,-5,8,-1,-2,-8,-1,5,-3,-5,4,2,-5,-4,4,7]), - vec![vec![-10,2,8],vec![-10,3,7],vec![-10,4,6],vec![-10,5,5],vec![-9,2,7],vec![-9,3,6],vec![-9,4,5],vec![-8,2,6],vec![-8,3,5],vec![-8,4,4],vec![-7,-1,8],vec![-7,2,5],vec![-7,3,4],vec![-6,-2,8],vec![-6,-1,7],vec![-6,2,4],vec![-5,-3,8],vec![-5,-2,7],vec![-5,-1,6],vec![-5,2,3],vec![-4,-4,8],vec![-4,-3,7],vec![-4,-2,6],vec![-4,-1,5],vec![-3,-2,5],vec![-3,-1,4],vec![-2,-1,3],vec![-1,-1,2]] + assert_eq!( + Solution::three_sum(vec![-1, 0, 1, 2, -1, -4]), + vec![vec![-1, -1, 2], vec![-1, 0, 1]] + ); + assert_eq!( + Solution::three_sum(vec![ + -7, -4, -6, 6, 4, -6, -9, -10, -7, 5, 3, -1, -5, 8, -1, -2, -8, -1, 5, -3, -5, 4, + 2, -5, -4, 4, 7 + ]), + vec![ + vec![-10, 2, 8], + vec![-10, 3, 7], + vec![-10, 4, 6], + vec![-10, 5, 5], + vec![-9, 2, 7], + vec![-9, 3, 6], + vec![-9, 4, 5], + vec![-8, 2, 6], + vec![-8, 3, 5], + vec![-8, 4, 4], + vec![-7, -1, 8], + vec![-7, 2, 5], + vec![-7, 3, 4], + vec![-6, -2, 8], + vec![-6, -1, 7], + vec![-6, 2, 4], + vec![-5, -3, 8], + vec![-5, -2, 7], + vec![-5, -1, 6], + vec![-5, 2, 3], + vec![-4, -4, 8], + vec![-4, -3, 7], + vec![-4, -2, 6], + vec![-4, -1, 5], + vec![-3, -2, 5], + vec![-3, -1, 4], + vec![-2, -1, 3], + vec![-1, -1, 2] + ] + ); + assert_eq!( + Solution::three_sum(vec![2, 0, -2, -5, -5, -3, 2, -4]), + vec![vec![-4, 2, 2], vec![-2, 0, 2]] ); - assert_eq!(Solution::three_sum(vec![2,0,-2,-5,-5,-3,2,-4]), - vec![vec![-4, 2, 2], vec![-2, 0, 2]]); let empty_vec: Vec> = vec![]; assert_eq!(Solution::three_sum(vec![]), empty_vec); } diff --git a/src/n0016_3sum_closest.rs b/src/n0016_3sum_closest.rs index f4f34dd7..eee265b5 100644 --- a/src/n0016_3sum_closest.rs +++ b/src/n0016_3sum_closest.rs @@ -2,15 +2,15 @@ * [16] 3Sum Closest * * Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. - * + * * Example: - * - * + * + * * Given array nums = [-1, 2, 1, -4], and target = 1. - * + * * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). - * - * + * + * */ pub struct Solution {} @@ -23,10 +23,12 @@ impl Solution { nums.sort(); let mut i = 0; while i < nums.len() - 2 { - let sub_min = Solution::two_sum_closest(&nums[(i+1)..nums.len()], target - nums[i]); + let sub_min = Solution::two_sum_closest(&nums[(i + 1)..nums.len()], target - nums[i]); if sub_min.abs() < min_distance.abs() { min_distance = sub_min; - if min_distance == 0 { break } + if min_distance == 0 { + break; + } } i += 1; } @@ -38,9 +40,13 @@ impl Solution { let mut local_min = i32::max_value(); while i < j { let sum = nums[i] + nums[j]; - if sum > target { j -= 1; } - else if sum < target { i += 1; } - else { return 0 } + if sum > target { + j -= 1; + } else if sum < target { + i += 1; + } else { + return 0; + } if (sum - target).abs() < local_min.abs() { local_min = sum - target } @@ -59,6 +65,9 @@ mod tests { fn test_16() { assert_eq!(Solution::three_sum_closest(vec![-1, 2, 1, -4], 1), 2); assert_eq!(Solution::three_sum_closest(vec![1, 2, 3], 1), 6); - assert_eq!(Solution::three_sum_closest(vec![1,2,4,8,16,32,64,128], 82), 82); + assert_eq!( + Solution::three_sum_closest(vec![1, 2, 4, 8, 16, 32, 64, 128], 82), + 82 + ); } } diff --git a/src/n0017_letter_combinations_of_a_phone_number.rs b/src/n0017_letter_combinations_of_a_phone_number.rs index b0dd49b5..ccd30a82 100644 --- a/src/n0017_letter_combinations_of_a_phone_number.rs +++ b/src/n0017_letter_combinations_of_a_phone_number.rs @@ -2,22 +2,22 @@ * [17] Letter Combinations of a Phone Number * * Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. - * + * * A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. - * + * * - * + * * Example: - * - * + * + * * Input: "23" * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. - * - * + * + * * Note: - * + * * Although the above answer is in lexicographical order, your answer could be in any order you want. - * + * */ pub struct Solution {} @@ -28,11 +28,19 @@ impl Solution { // '0' and '1' as placeholder to avoid index shifting let table: Vec<(char, Vec)> = vec![ ('0', vec![]), - ('1', vec![]), ('2', vec!['a','b','c']), ('3', vec!['d','e','f']), - ('4', vec!['g','h','i']), ('5', vec!['j','k','l']), ('6', vec!['m','n','o']), - ('7', vec!['p','q','r','s']), ('8', vec!['t','u','v']), ('9', vec!['w','x','y','z']) + ('1', vec![]), + ('2', vec!['a', 'b', 'c']), + ('3', vec!['d', 'e', 'f']), + ('4', vec!['g', 'h', 'i']), + ('5', vec!['j', 'k', 'l']), + ('6', vec!['m', 'n', 'o']), + ('7', vec!['p', 'q', 'r', 's']), + ('8', vec!['t', 'u', 'v']), + ('9', vec!['w', 'x', 'y', 'z']), ]; - if digits.len() < 1 { return vec![] } + if digits.len() < 1 { + return vec![]; + } let mut combs: Vec = vec![String::with_capacity(digits.len())]; for ch in digits.chars().into_iter() { let chs = &table[ch.to_digit(10).unwrap() as usize].1; @@ -62,6 +70,9 @@ mod tests { #[test] fn test_17() { - assert_eq!(Solution::letter_combinations("23".to_string()), ["cf", "af", "bf", "cd", "ce", "ad", "ae", "bd", "be"]); + assert_eq!( + Solution::letter_combinations("23".to_string()), + ["cf", "af", "bf", "cd", "ce", "ad", "ae", "bd", "be"] + ); } } diff --git a/src/n0018_4sum.rs b/src/n0018_4sum.rs index ac6561fe..f74fa5ed 100644 --- a/src/n0018_4sum.rs +++ b/src/n0018_4sum.rs @@ -2,24 +2,24 @@ * [18] 4Sum * * Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. - * + * * Note: - * + * * The solution set must not contain duplicate quadruplets. - * + * * Example: - * - * + * + * * Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. - * + * * A solution set is: * [ * [-1, 0, 0, 1], * [-2, -1, 1, 2], * [-2, 0, 0, 2] * ] - * - * + * + * */ pub struct Solution {} @@ -32,19 +32,25 @@ use std::collections::BTreeMap; use std::collections::HashSet; impl Solution { pub fn four_sum(nums: Vec, target: i32) -> Vec> { - if nums.len() < 4 { return vec![] } + if nums.len() < 4 { + return vec![]; + } let mut set: HashSet> = HashSet::new(); let mut map: BTreeMap> = BTreeMap::new(); // collect two-sums in asc order, store the index to avoid single number reusing for i in 0..(nums.len() - 1) { for j in (i + 1)..nums.len() { - map.entry(nums[i] + nums[j]).or_insert(Vec::new()).push((i, j)); + map.entry(nums[i] + nums[j]) + .or_insert(Vec::new()) + .push((i, j)); } } // find results for (&sum, pairs) in map.iter() { // avoid duplicates - if sum > target / 2 { break; } + if sum > target / 2 { + break; + } match map.get(&(target - sum)) { None => continue, // 2-sum + 2-sum == target, then all the possible combination @@ -52,10 +58,15 @@ impl Solution { Some(subs) => { for pair in pairs.iter() { for sub in subs.iter() { - if sub.0 == pair.0 || sub.0 == pair.1 || sub.1 == pair.0 || sub.1 == pair.1 { - continue + if sub.0 == pair.0 + || sub.0 == pair.1 + || sub.1 == pair.0 + || sub.1 == pair.1 + { + continue; } - let mut vec = vec![nums[pair.0], nums[pair.1], nums[sub.0], nums[sub.1]]; + let mut vec = + vec![nums[pair.0], nums[pair.1], nums[sub.0], nums[sub.1]]; vec.sort(); set.insert(vec); } @@ -77,10 +88,9 @@ mod tests { #[test] #[ignore] fn test_18() { - assert_eq!(Solution::four_sum(vec![1, 0, -1, 0, -2, 2], 0), vec![ - vec![-1, 0, 0, 1], - vec![-2, 0, 0, 2], - vec![-2, -1, 1, 2] - ]); + assert_eq!( + Solution::four_sum(vec![1, 0, -1, 0, -2, 2], 0), + vec![vec![-1, 0, 0, 1], vec![-2, 0, 0, 2], vec![-2, -1, 1, 2]] + ); } } diff --git a/src/n0019_remove_nth_node_from_end_of_list.rs b/src/n0019_remove_nth_node_from_end_of_list.rs index e064852f..a1698a45 100644 --- a/src/n0019_remove_nth_node_from_end_of_list.rs +++ b/src/n0019_remove_nth_node_from_end_of_list.rs @@ -1,28 +1,27 @@ - /** * [19] Remove Nth Node From End of List * * Given a linked list, remove the n-th node from the end of list and return its head. - * + * * Example: - * - * + * + * * Given linked list: 1->2->3->4->5, and n = 2. - * + * * After removing the second node from the end, the linked list becomes 1->2->3->5. - * - * + * + * * Note: - * + * * Given n will always be valid. - * + * * Follow up: - * + * * Could you do this in one pass? - * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here @@ -30,9 +29,7 @@ use super::util::linked_list::{ListNode, to_list}; // but two pass don't takes longer time impl Solution { pub fn remove_nth_from_end(head: Option>, n: i32) -> Option> { - let mut dummy_head = Some(Box::new(ListNode { - val: 0, next: head, - })); + let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head })); let mut len = 0; { let mut p = dummy_head.as_ref(); @@ -62,9 +59,10 @@ mod tests { #[test] fn test_19() { - assert_eq!(Solution::remove_nth_from_end(to_list(vec![1,2,3,4,5]), 2), - to_list(vec![1,2,3,5])); - assert_eq!(Solution::remove_nth_from_end(to_list(vec![1]), 1), - None); + assert_eq!( + Solution::remove_nth_from_end(to_list(vec![1, 2, 3, 4, 5]), 2), + to_list(vec![1, 2, 3, 5]) + ); + assert_eq!(Solution::remove_nth_from_end(to_list(vec![1]), 1), None); } } diff --git a/src/n0020_valid_parentheses.rs b/src/n0020_valid_parentheses.rs index 69b28393..2af69c67 100644 --- a/src/n0020_valid_parentheses.rs +++ b/src/n0020_valid_parentheses.rs @@ -2,51 +2,51 @@ * [20] Valid Parentheses * * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. - * + * * An input string is valid if: - * + * *
    * Open brackets must be closed by the same type of brackets. * Open brackets must be closed in the correct order. *
- * + * * Note that an empty string is also considered valid. - * + * * Example 1: - * - * + * + * * Input: "()" * Output: true - * - * + * + * * Example 2: - * - * + * + * * Input: "()[]{}" * Output: true - * - * + * + * * Example 3: - * - * + * + * * Input: "(]" * Output: false - * - * + * + * * Example 4: - * - * + * + * * Input: "([)]" * Output: false - * - * + * + * * Example 5: - * - * + * + * * Input: "{[]}" * Output: true - * - * + * + * */ pub struct Solution {} @@ -57,13 +57,13 @@ impl Solution { let mut stack: Vec = Vec::new(); for ch in s.chars().into_iter() { match stack.last() { - None => {}, + None => {} Some(&last) => { if Solution::pair(last, ch) { stack.pop(); - continue + continue; } - }, + } } stack.push(ch); } @@ -72,9 +72,9 @@ impl Solution { #[inline(always)] fn pair(open: char, close: char) -> bool { - (open == '{' && close == '}') || - (open == '(' && close == ')') || - (open == '[' && close == ']') + (open == '{' && close == '}') + || (open == '(' && close == ')') + || (open == '[' && close == ']') } } diff --git a/src/n0021_merge_two_sorted_lists.rs b/src/n0021_merge_two_sorted_lists.rs index b8d26180..5a25adf7 100644 --- a/src/n0021_merge_two_sorted_lists.rs +++ b/src/n0021_merge_two_sorted_lists.rs @@ -2,39 +2,44 @@ * [21] Merge Two Sorted Lists * * Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. - * + * * Example: - * + * * Input: 1->2->4, 1->3->4 * Output: 1->1->2->3->4->4 - * - * + * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here // recursive will be much easier to understand impl Solution { - pub fn merge_two_lists(l1: Option>, l2: Option>) -> Option> { - let mut dummy_head = Some(Box::new(ListNode{ - val: 0, next: None, - })); + pub fn merge_two_lists( + l1: Option>, + l2: Option>, + ) -> Option> { + let mut dummy_head = Some(Box::new(ListNode { val: 0, next: None })); let mut head = &mut dummy_head; let (mut l1, mut l2) = (l1, l2); while l1.is_some() || l2.is_some() { if l1.is_none() { - head.as_mut().unwrap().next = l2; break; + head.as_mut().unwrap().next = l2; + break; } else if l2.is_none() { - head.as_mut().unwrap().next = l1; break; + head.as_mut().unwrap().next = l1; + break; } let next = if l1.as_ref().unwrap().val < l2.as_ref().unwrap().val { let (origin, next) = Solution::take_head(l1); - l1 = origin; next + l1 = origin; + next } else { let (origin, next) = Solution::take_head(l2); - l2 = origin; next + l2 = origin; + next }; head.as_mut().unwrap().next = next; head = &mut head.as_mut().unwrap().next; @@ -59,6 +64,9 @@ mod tests { #[test] fn test_21() { - assert_eq!(Solution::merge_two_lists(to_list(vec![1,2,4]), to_list(vec![1,3,4])), to_list(vec![1,1,2,3,4,4])); + assert_eq!( + Solution::merge_two_lists(to_list(vec![1, 2, 4]), to_list(vec![1, 3, 4])), + to_list(vec![1, 1, 2, 3, 4, 4]) + ); } } diff --git a/src/n0022_generate_parentheses.rs b/src/n0022_generate_parentheses.rs index d8fefa65..887aa213 100644 --- a/src/n0022_generate_parentheses.rs +++ b/src/n0022_generate_parentheses.rs @@ -1,14 +1,14 @@ /** * [22] Generate Parentheses * - * + * * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. - * - * - * + * + * + * * For example, given n = 3, a solution set is: - * - * + * + * * [ * "((()))", * "(()())", @@ -16,7 +16,7 @@ * "()(())", * "()()()" * ] - * + * */ pub struct Solution {} @@ -25,7 +25,9 @@ pub struct Solution {} // DFS impl Solution { pub fn generate_parenthesis(n: i32) -> Vec { - if n < 1 { return vec![] } + if n < 1 { + return vec![]; + } let mut result = Vec::new(); Solution::dfs(n, 0, 0, &mut result, String::new()); result @@ -57,14 +59,11 @@ mod tests { #[test] fn test_22() { - assert_eq!(Solution::generate_parenthesis(1), vec!["()"] ); - assert_eq!(Solution::generate_parenthesis(2), vec!["(())", "()()"] ); - assert_eq!(Solution::generate_parenthesis(3), vec![ - "((()))", - "(()())", - "(())()", - "()(())", - "()()()" - ] ); + assert_eq!(Solution::generate_parenthesis(1), vec!["()"]); + assert_eq!(Solution::generate_parenthesis(2), vec!["(())", "()()"]); + assert_eq!( + Solution::generate_parenthesis(3), + vec!["((()))", "(()())", "(())()", "()(())", "()()()"] + ); } } diff --git a/src/n0023_merge_k_sorted_lists.rs b/src/n0023_merge_k_sorted_lists.rs index 8c292094..74b95045 100644 --- a/src/n0023_merge_k_sorted_lists.rs +++ b/src/n0023_merge_k_sorted_lists.rs @@ -2,10 +2,10 @@ * [23] Merge k Sorted Lists * * Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. - * + * * Example: - * - * + * + * * Input: * [ * 1->4->5, @@ -13,15 +13,15 @@ * 2->6 * ] * Output: 1->1->2->3->4->4->5->6 - * - * + * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here -use std::collections::BinaryHeap; use std::cmp::Ordering; +use std::collections::BinaryHeap; // head value and the index struct Node(i32, usize); @@ -48,17 +48,22 @@ impl Solution { pub fn merge_k_lists(lists: Vec>>) -> Option> { let mut heap: BinaryHeap = BinaryHeap::new(); for (idx, node) in lists.iter().enumerate() { - node.as_ref().and_then(|n| Some(heap.push(Node(n.val, idx)))); + node.as_ref() + .and_then(|n| Some(heap.push(Node(n.val, idx)))); } Solution::next(lists, &mut heap) } - fn next(mut lists: Vec>>, heap: &mut BinaryHeap ) -> Option> { + fn next( + mut lists: Vec>>, + heap: &mut BinaryHeap, + ) -> Option> { heap.pop().map(|node| { let next = lists[node.1].take().unwrap().next; - next.as_ref().and_then(|n| Some(heap.push(Node(n.val, node.1)))); + next.as_ref() + .and_then(|n| Some(heap.push(Node(n.val, node.1)))); lists[node.1] = next; - Box::new(ListNode{ + Box::new(ListNode { val: node.0, next: Solution::next(lists, heap), }) @@ -74,16 +79,14 @@ mod tests { #[test] fn test_23() { - assert_eq!(Solution::merge_k_lists( - vec![ - to_list(vec![1,4,5]), - to_list(vec![1,3,4]), - to_list(vec![2,6]), + assert_eq!( + Solution::merge_k_lists(vec![ + to_list(vec![1, 4, 5]), + to_list(vec![1, 3, 4]), + to_list(vec![2, 6]), ]), - to_list(vec![1,1,2,3,4,4,5,6]) - ); - assert_eq!(Solution::merge_k_lists(vec![]), - None + to_list(vec![1, 1, 2, 3, 4, 4, 5, 6]) ); + assert_eq!(Solution::merge_k_lists(vec![]), None); } } diff --git a/src/n0024_swap_nodes_in_pairs.rs b/src/n0024_swap_nodes_in_pairs.rs index c9401bd5..41e3c6c4 100644 --- a/src/n0024_swap_nodes_in_pairs.rs +++ b/src/n0024_swap_nodes_in_pairs.rs @@ -2,32 +2,34 @@ * [24] Swap Nodes in Pairs * * Given a linked list, swap every two adjacent nodes and return its head. - * + * * Example: - * - * + * + * * Given 1->2->3->4, you should return the list as 2->1->4->3. - * + * * Note: - * - * + * + * * Your algorithm should use only constant extra space. * You may not modify the values in the list's nodes, only nodes itself may be changed. - * - * + * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here impl Solution { pub fn swap_pairs(head: Option>) -> Option> { - let mut dummy_head = Some(Box::new(ListNode{val: 0, next: head})); + let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head })); let mut head = dummy_head.as_mut(); loop { let mut left = head.as_mut().unwrap().next.take(); - if left.is_none() { break } + if left.is_none() { + break; + } let mut right = left.as_mut().unwrap().next.take(); // handle the un-paired one, e.g. [1, 2, 3] -> [2, 1, 3], 3 is un-paired if right.is_none() { @@ -54,9 +56,15 @@ mod tests { #[test] fn test_24() { - assert_eq!(Solution::swap_pairs(to_list(vec![1, 2, 3, 4])), to_list(vec![2, 1, 4, 3])); + assert_eq!( + Solution::swap_pairs(to_list(vec![1, 2, 3, 4])), + to_list(vec![2, 1, 4, 3]) + ); assert_eq!(Solution::swap_pairs(to_list(vec![])), to_list(vec![])); - assert_eq!(Solution::swap_pairs(to_list(vec![1, 2, 3])), to_list(vec![2, 1, 3])); + assert_eq!( + Solution::swap_pairs(to_list(vec![1, 2, 3])), + to_list(vec![2, 1, 3]) + ); assert_eq!(Solution::swap_pairs(to_list(vec![1])), to_list(vec![1])); } } diff --git a/src/n0025_reverse_nodes_in_k_group.rs b/src/n0025_reverse_nodes_in_k_group.rs index 6e8c21f0..aac987f7 100644 --- a/src/n0025_reverse_nodes_in_k_group.rs +++ b/src/n0025_reverse_nodes_in_k_group.rs @@ -2,46 +2,48 @@ * [25] Reverse Nodes in k-Group * * Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. - * + * * k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. - * - * - * - * + * + * + * + * * Example: - * + * * Given this linked list: 1->2->3->4->5 - * + * * For k = 2, you should return: 2->1->4->3->5 - * + * * For k = 3, you should return: 3->2->1->4->5 - * + * * Note: - * - * + * + * * Only constant extra memory is allowed. * You may not alter the values in the list's nodes, only nodes itself may be changed. - * - * + * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here impl Solution { pub fn reverse_k_group(head: Option>, k: i32) -> Option> { - let mut dummy_head = Some(Box::new(ListNode{val: 0, next: head})); + let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head })); let mut head = dummy_head.as_mut(); 'outer: loop { let mut start = head.as_mut().unwrap().next.take(); - if start.is_none() { break 'outer } + if start.is_none() { + break 'outer; + } let mut end = start.as_mut(); - for _ in 0..(k-1) { + for _ in 0..(k - 1) { end = end.unwrap().next.as_mut(); if end.is_none() { head.as_mut().unwrap().next = start; - break 'outer + break 'outer; } } let mut tail = end.as_mut().unwrap().next.take(); @@ -57,7 +59,10 @@ impl Solution { } #[inline(always)] - fn reverse(mut head: Option>, tail: Option>) -> Option> { + fn reverse( + mut head: Option>, + tail: Option>, + ) -> Option> { let mut prev = tail; let mut current = head; while let Some(mut current_node_inner) = current { @@ -78,13 +83,21 @@ mod tests { #[test] fn test_25() { - assert_eq!(Solution::reverse_k_group(to_list(vec![1,2,3,4,5]), 2), - to_list(vec![2,1,4,3,5])); - assert_eq!(Solution::reverse_k_group(to_list(vec![1,2,3,4,5]), 3), - to_list(vec![3,2,1,4,5])); - assert_eq!(Solution::reverse_k_group(to_list(vec![1,2,3,4,5]), 5), - to_list(vec![5,4,3,2,1])); - assert_eq!(Solution::reverse_k_group(to_list(vec![1]), 1), - to_list(vec![1])); + assert_eq!( + Solution::reverse_k_group(to_list(vec![1, 2, 3, 4, 5]), 2), + to_list(vec![2, 1, 4, 3, 5]) + ); + assert_eq!( + Solution::reverse_k_group(to_list(vec![1, 2, 3, 4, 5]), 3), + to_list(vec![3, 2, 1, 4, 5]) + ); + assert_eq!( + Solution::reverse_k_group(to_list(vec![1, 2, 3, 4, 5]), 5), + to_list(vec![5, 4, 3, 2, 1]) + ); + assert_eq!( + Solution::reverse_k_group(to_list(vec![1]), 1), + to_list(vec![1]) + ); } } diff --git a/src/n0026_remove_duplicates_from_sorted_array.rs b/src/n0026_remove_duplicates_from_sorted_array.rs index c5794fac..c4b07180 100644 --- a/src/n0026_remove_duplicates_from_sorted_array.rs +++ b/src/n0026_remove_duplicates_from_sorted_array.rs @@ -2,46 +2,46 @@ * [26] Remove Duplicates from Sorted Array * * Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. - * + * * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. - * + * * Example 1: - * - * + * + * * Given nums = [1,1,2], - * + * * Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. - * + * * It doesn't matter what you leave beyond the returned length. - * + * * Example 2: - * - * + * + * * Given nums = [0,0,1,1,1,2,2,3,3,4], - * + * * Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. - * + * * It doesn't matter what values are set beyond the returned length. - * - * + * + * * Clarification: - * + * * Confused why the returned value is an integer but your answer is an array? - * + * * Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. - * + * * Internally you can think of this: - * - * + * + * * // nums is passed in by reference. (i.e., without making a copy) * int len = removeDuplicates(nums); - * + * * // any modification to nums in your function would be known by the caller. * // using the length returned by your function, it prints the first len elements. * for (int i = 0; i < len; i++) { * print(nums[i]); * } - * + * */ pub struct Solution {} @@ -73,11 +73,11 @@ mod tests { #[test] fn test_26() { assert_eq!(Solution::remove_duplicates(&mut vec![]), 0); - let mut vec1 = vec![1,1,1,1,3]; + let mut vec1 = vec![1, 1, 1, 1, 3]; assert_eq!(Solution::remove_duplicates(&mut vec1), 2); - assert_eq!(vec1, vec![1,3]); - let mut vec2 = vec![1,1,2]; + assert_eq!(vec1, vec![1, 3]); + let mut vec2 = vec![1, 1, 2]; assert_eq!(Solution::remove_duplicates(&mut vec2), 2); - assert_eq!(vec2, vec![1,2]); + assert_eq!(vec2, vec![1, 2]); } } diff --git a/src/n0027_remove_element.rs b/src/n0027_remove_element.rs index a5668734..5c11843b 100644 --- a/src/n0027_remove_element.rs +++ b/src/n0027_remove_element.rs @@ -2,50 +2,50 @@ * [27] Remove Element * * Given an array nums and a value val, remove all instances of that value in-place and return the new length. - * + * * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. - * + * * The order of elements can be changed. It doesn't matter what you leave beyond the new length. - * + * * Example 1: - * - * + * + * * Given nums = [3,2,2,3], val = 3, - * + * * Your function should return length = 2, with the first two elements of nums being 2. - * + * * It doesn't matter what you leave beyond the returned length. - * - * + * + * * Example 2: - * - * + * + * * Given nums = [0,1,2,2,3,0,4,2], val = 2, - * + * * Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. - * + * * Note that the order of those five elements can be arbitrary. - * + * * It doesn't matter what values are set beyond the returned length. - * + * * Clarification: - * + * * Confused why the returned value is an integer but your answer is an array? - * + * * Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. - * + * * Internally you can think of this: - * - * + * + * * // nums is passed in by reference. (i.e., without making a copy) * int len = removeElement(nums, val); - * + * * // any modification to nums in your function would be known by the caller. * // using the length returned by your function, it prints the first len elements. * for (int i = 0; i < len; i++) { * print(nums[i]); * } - * + * */ pub struct Solution {} @@ -53,11 +53,13 @@ pub struct Solution {} impl Solution { pub fn remove_element(nums: &mut Vec, val: i32) -> i32 { - if nums.len() < 1 { return 0 } - let (mut start, mut end) = (0_usize, nums.len()-1); + if nums.len() < 1 { + return 0; + } + let (mut start, mut end) = (0_usize, nums.len() - 1); while start < end { if nums[start] == val { - nums[start] = nums[end-1]; + nums[start] = nums[end - 1]; end -= 1; } else { start += 1; @@ -75,12 +77,18 @@ mod tests { #[test] fn test_27() { - let mut vec1 = vec![0,1,2,2,3,0,4,2]; + let mut vec1 = vec![0, 1, 2, 2, 3, 0, 4, 2]; assert_eq!(Solution::remove_element(&mut vec1, 2), 5); - assert_eq!(vec1[0..5], [0,1,4,0,3]); + assert_eq!(vec1[0..5], [0, 1, 4, 0, 3]); assert_eq!(Solution::remove_element(&mut vec![], 2), 0); - assert_eq!(Solution::remove_element(&mut vec![1,2,2,2,2,2,2], 2), 1); - assert_eq!(Solution::remove_element(&mut vec![2,2,2,2,2,2,2], 2), 0); + assert_eq!( + Solution::remove_element(&mut vec![1, 2, 2, 2, 2, 2, 2], 2), + 1 + ); + assert_eq!( + Solution::remove_element(&mut vec![2, 2, 2, 2, 2, 2, 2], 2), + 0 + ); assert_eq!(Solution::remove_element(&mut vec![1], 1), 0); } } diff --git a/src/n0028_implement_strstr.rs b/src/n0028_implement_strstr.rs index 62000791..b4bbee26 100644 --- a/src/n0028_implement_strstr.rs +++ b/src/n0028_implement_strstr.rs @@ -2,29 +2,29 @@ * [28] Implement strStr() * * Implement strStr(). - * + * * Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. - * + * * Example 1: - * - * + * + * * Input: haystack = "hello", needle = "ll" * Output: 2 - * - * + * + * * Example 2: - * - * + * + * * Input: haystack = "aaaaa", needle = "bba" * Output: -1 - * - * + * + * * Clarification: - * + * * What should we return when needle is an empty string? This is a great question to ask during an interview. - * + * * For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). - * + * */ pub struct Solution {} @@ -32,7 +32,9 @@ pub struct Solution {} impl Solution { pub fn str_str(haystack: String, needle: String) -> i32 { - if needle.is_empty() { return 0 } + if needle.is_empty() { + return 0; + } haystack.find(&needle).map_or(-1_i32, |v| v as i32) } } diff --git a/src/n0029_divide_two_integers.rs b/src/n0029_divide_two_integers.rs index 2e1c9699..edff4f40 100644 --- a/src/n0029_divide_two_integers.rs +++ b/src/n0029_divide_two_integers.rs @@ -2,31 +2,31 @@ * [29] Divide Two Integers * * Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. - * + * * Return the quotient after dividing dividend by divisor. - * + * * The integer division should truncate toward zero. - * + * * Example 1: - * - * + * + * * Input: dividend = 10, divisor = 3 * Output: 3 - * + * * Example 2: - * - * + * + * * Input: dividend = 7, divisor = -3 * Output: -2 - * + * * Note: - * - * + * + * * Both dividend and divisor will be 32-bit signed integers. * The divisor will never be 0. * Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31, 2^31 - 1]. For the purpose of this problem, assume that your function returns 2^31 - 1 when the division result overflows. - * - * + * + * */ pub struct Solution {} @@ -45,6 +45,5 @@ mod tests { use super::*; #[test] - fn test_29() { - } + fn test_29() {} } diff --git a/src/n0030_substring_with_concatenation_of_all_words.rs b/src/n0030_substring_with_concatenation_of_all_words.rs index 81dd6e5f..1c797090 100644 --- a/src/n0030_substring_with_concatenation_of_all_words.rs +++ b/src/n0030_substring_with_concatenation_of_all_words.rs @@ -2,27 +2,27 @@ * [30] Substring with Concatenation of All Words * * You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. - * + * * Example 1: - * - * + * + * * Input: * s = "barfoothefoobarman", * words = ["foo","bar"] * Output: [0,9] * Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively. * The output order does not matter, returning [9,0] is fine too. - * - * + * + * * Example 2: - * - * + * + * * Input: * s = "wordgoodgoodgoodbestword", * words = ["word","good","best","word"] * Output: [] - * - * + * + * */ pub struct Solution {} @@ -33,7 +33,7 @@ struct Term { } impl Term { fn new(expect: i32, count: i32) -> Self { - Term{expect, count} + Term { expect, count } } fn inc_expect(&mut self) { self.expect += 1; @@ -52,14 +52,18 @@ impl Term { } } -use std::collections::HashMap; use std::collections::hash_map::Entry; +use std::collections::HashMap; impl Solution { pub fn find_substring(s: String, words: Vec) -> Vec { - if words.len() < 1 { return vec![] } + if words.len() < 1 { + return vec![]; + } let word_len = words[0].len(); - if word_len < 1 { return vec![] } + if word_len < 1 { + return vec![]; + } let substr_len = word_len * words.len(); let mut map: HashMap<&str, Term> = HashMap::with_capacity(words.len()); for word in words.iter() { @@ -72,16 +76,18 @@ impl Solution { let mut j = shift; // we do a sliding window for each round while j + word_len - 1 < s.len() { - match map.entry(&s[j..j+word_len]) { + match map.entry(&s[j..j + word_len]) { Entry::Occupied(mut entry) => { entry.get_mut().inc(); // term exhausted, shrink the window to release if entry.get().exhausted() { while i < j { - let term = &s[i..i+word_len]; + let term = &s[i..i + word_len]; map.entry(term).and_modify(|t| t.dec()); i += word_len; - if term == &s[j..j+word_len] { break } + if term == &s[j..j + word_len] { + break; + } } j += word_len; } else { @@ -91,16 +97,18 @@ impl Solution { // matched! result.push(i as i32); // move the whole window, release the dropped term - map.entry(&s[i..i+word_len]).and_modify(|t| t.dec()); - j += word_len; i += word_len; + map.entry(&s[i..i + word_len]).and_modify(|t| t.dec()); + j += word_len; + i += word_len; } } - }, + } // bad term, move over and do a reset Entry::Vacant(entry) => { map.iter_mut().for_each(|(_, v)| v.reset()); - j += word_len; i = j; - }, + j += word_len; + i = j; + } } } map.iter_mut().for_each(|(_, v)| v.reset()) @@ -117,16 +125,48 @@ mod tests { #[test] fn test_30() { - assert_eq!(Solution::find_substring("barfoothefoobarman".to_string(), vec!["foo".to_string(),"bar".to_string()]), - vec![0, 9]); - assert_eq!(Solution::find_substring("wordgoodgoodgoodbestword".to_string(), - vec!["word".to_string(),"good".to_string(), "best".to_string(), "word".to_string()]), - vec![]); - assert_eq!(Solution::find_substring("wordgoodgoodgoodbestword".to_string(), - vec!["word".to_string(),"good".to_string(), "best".to_string(), "good".to_string()]), - vec![8]); - assert_eq!(Solution::find_substring("xxwordgoodgoodgoodbestword".to_string(), - vec!["word".to_string(),"good".to_string(), "best".to_string(), "good".to_string()]), - vec![10]); + assert_eq!( + Solution::find_substring( + "barfoothefoobarman".to_string(), + vec!["foo".to_string(), "bar".to_string()] + ), + vec![0, 9] + ); + assert_eq!( + Solution::find_substring( + "wordgoodgoodgoodbestword".to_string(), + vec![ + "word".to_string(), + "good".to_string(), + "best".to_string(), + "word".to_string() + ] + ), + vec![] + ); + assert_eq!( + Solution::find_substring( + "wordgoodgoodgoodbestword".to_string(), + vec![ + "word".to_string(), + "good".to_string(), + "best".to_string(), + "good".to_string() + ] + ), + vec![8] + ); + assert_eq!( + Solution::find_substring( + "xxwordgoodgoodgoodbestword".to_string(), + vec![ + "word".to_string(), + "good".to_string(), + "best".to_string(), + "good".to_string() + ] + ), + vec![10] + ); } } diff --git a/src/n0031_next_permutation.rs b/src/n0031_next_permutation.rs index 39e615d9..459693ec 100644 --- a/src/n0031_next_permutation.rs +++ b/src/n0031_next_permutation.rs @@ -2,17 +2,17 @@ * [31] Next Permutation * * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. - * + * * If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). - * + * * The replacement must be in-place and use only constant extra memory. - * + * * Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. - * + * * 1,2,3 → 1,3,2
* 3,2,1 → 1,2,3
* 1,1,5 → 1,5,1 - * + * */ pub struct Solution {} @@ -43,7 +43,7 @@ impl Solution { j -= 1; } } - let slice = &mut nums[((i+1) as usize)..len]; + let slice = &mut nums[((i + 1) as usize)..len]; slice.reverse(); } } @@ -75,12 +75,12 @@ mod tests { #[test] fn test_31() { - let mut vec1 = vec![1,2,3,4,5]; + let mut vec1 = vec![1, 2, 3, 4, 5]; Solution::next_permutation(&mut vec1); - assert_eq!(vec1, vec![1,2,3,5,4]); + assert_eq!(vec1, vec![1, 2, 3, 5, 4]); - let mut vec2 = vec![5,4,3,2,1]; + let mut vec2 = vec![5, 4, 3, 2, 1]; Solution::next_permutation(&mut vec2); - assert_eq!(vec2, vec![1,2,3,4,5]); + assert_eq!(vec2, vec![1, 2, 3, 4, 5]); } } diff --git a/src/n0032_longest_valid_parentheses.rs b/src/n0032_longest_valid_parentheses.rs index c098bfba..c6949519 100644 --- a/src/n0032_longest_valid_parentheses.rs +++ b/src/n0032_longest_valid_parentheses.rs @@ -2,23 +2,23 @@ * [32] Longest Valid Parentheses * * Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. - * + * * Example 1: - * - * + * + * * Input: "(()" * Output: 2 * Explanation: The longest valid parentheses substring is "()" - * - * + * + * * Example 2: - * - * + * + * * Input: ")()())" * Output: 4 * Explanation: The longest valid parentheses substring is "()()" - * - * + * + * */ pub struct Solution {} @@ -69,12 +69,24 @@ mod tests { assert_eq!(Solution::longest_valid_parentheses(")()())".to_string()), 4); assert_eq!(Solution::longest_valid_parentheses(")(".to_string()), 0); assert_eq!(Solution::longest_valid_parentheses("(()".to_string()), 2); - assert_eq!(Solution::longest_valid_parentheses("(((((()()".to_string()), 4); - assert_eq!(Solution::longest_valid_parentheses("((((((((()))".to_string()), 6); + assert_eq!( + Solution::longest_valid_parentheses("(((((()()".to_string()), + 4 + ); + assert_eq!( + Solution::longest_valid_parentheses("((((((((()))".to_string()), + 6 + ); assert_eq!(Solution::longest_valid_parentheses("()".to_string()), 2); assert_eq!(Solution::longest_valid_parentheses("()(()".to_string()), 2); - assert_eq!(Solution::longest_valid_parentheses(")()(((())))(".to_string()), 10); - assert_eq!(Solution::longest_valid_parentheses("(()(((()".to_string()), 2); + assert_eq!( + Solution::longest_valid_parentheses(")()(((())))(".to_string()), + 10 + ); + assert_eq!( + Solution::longest_valid_parentheses("(()(((()".to_string()), + 2 + ); assert_eq!(Solution::longest_valid_parentheses("".to_string()), 0); } } diff --git a/src/n0034_find_first_and_last_position_of_element_in_sorted_array.rs b/src/n0034_find_first_and_last_position_of_element_in_sorted_array.rs index 2b1a5ba2..d13bfb86 100644 --- a/src/n0034_find_first_and_last_position_of_element_in_sorted_array.rs +++ b/src/n0034_find_first_and_last_position_of_element_in_sorted_array.rs @@ -2,23 +2,23 @@ * [34] Find First and Last Position of Element in Sorted Array * * Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. - * + * * Your algorithm's runtime complexity must be in the order of O(log n). - * + * * If the target is not found in the array, return [-1, -1]. - * + * * Example 1: - * - * + * + * * Input: nums = [5,7,7,8,8,10], target = 8 * Output: [3,4] - * + * * Example 2: - * - * + * + * * Input: nums = [5,7,7,8,8,10], target = 6 * Output: [-1,-1] - * + * */ pub struct Solution {} @@ -38,6 +38,5 @@ mod tests { use super::*; #[test] - fn test_34() { - } + fn test_34() {} } diff --git a/src/n0035_search_insert_position.rs b/src/n0035_search_insert_position.rs index 7eba236a..30921761 100644 --- a/src/n0035_search_insert_position.rs +++ b/src/n0035_search_insert_position.rs @@ -2,37 +2,37 @@ * [35] Search Insert Position * * Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. - * + * * You may assume no duplicates in the array. - * + * * Example 1: - * - * + * + * * Input: [1,3,5,6], 5 * Output: 2 - * - * + * + * * Example 2: - * - * + * + * * Input: [1,3,5,6], 2 * Output: 1 - * - * + * + * * Example 3: - * - * + * + * * Input: [1,3,5,6], 7 * Output: 4 - * - * + * + * * Example 4: - * - * + * + * * Input: [1,3,5,6], 0 * Output: 0 - * - * + * + * */ pub struct Solution {} @@ -52,6 +52,5 @@ mod tests { use super::*; #[test] - fn test_35() { - } + fn test_35() {} } diff --git a/src/n0036_valid_sudoku.rs b/src/n0036_valid_sudoku.rs index 2f8e8284..255bab22 100644 --- a/src/n0036_valid_sudoku.rs +++ b/src/n0036_valid_sudoku.rs @@ -2,21 +2,21 @@ * [36] Valid Sudoku * * Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: - * + * *
    * Each row must contain the digits 1-9 without repetition. * Each column must contain the digits 1-9 without repetition. * Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition. *
- * + * *
* A partially filled sudoku which is valid. - * + * * The Sudoku board could be partially filled, where empty cells are filled with the character '.'. - * + * * Example 1: - * - * + * + * * Input: * [ * ["5","3",".",".","7",".",".",".","."], @@ -30,11 +30,11 @@ * [".",".",".",".","8",".",".","7","9"] * ] * Output: true - * - * + * + * * Example 2: - * - * + * + * * Input: * [ * ["8","3",".",".","7",".",".",".","."], @@ -48,19 +48,19 @@ * [".",".",".",".","8",".",".","7","9"] * ] * Output: false - * Explanation: Same as Example 1, except with the 5 in the top left corner being + * Explanation: Same as Example 1, except with the 5 in the top left corner being * modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid. - * - * + * + * * Note: - * - * + * + * * A Sudoku board (partially filled) could be valid but is not necessarily solvable. * Only the filled cells need to be validated according to the mentioned rules. * The given board contain only digits 1-9 and the character '.'. * The given board size is always 9x9. - * - * + * + * */ pub struct Solution {} @@ -71,31 +71,55 @@ impl Solution { pub fn is_valid_sudoku(board: Vec>) -> bool { let mut table = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for row in board.iter() { - for z in 1..10 { table[z] = 0; } + for z in 1..10 { + table[z] = 0; + } for ch in row { match ch.to_digit(10) { - None => { continue }, - Some(idx) => {if table[idx as usize] > 0 { return false } else { table[idx as usize] = 1 }}, + None => continue, + Some(idx) => { + if table[idx as usize] > 0 { + return false; + } else { + table[idx as usize] = 1 + } + } } } } for i in 0..9 { - for z in 1..10 { table[z] = 0; } + for z in 1..10 { + table[z] = 0; + } for row in board.iter() { match row[i].to_digit(10) { - None => { continue }, - Some(idx) => {if table[idx as usize] > 0 { return false } else { table[idx as usize] = 1 }}, + None => continue, + Some(idx) => { + if table[idx as usize] > 0 { + return false; + } else { + table[idx as usize] = 1 + } + } } } } for i in 0..3 { for j in 0..3 { - for z in 1..10 { table[z] = 0; } - for row in 3*i..3*(i+1) { - for column in 3*j..3*(j+1) { + for z in 1..10 { + table[z] = 0; + } + for row in 3 * i..3 * (i + 1) { + for column in 3 * j..3 * (j + 1) { match board[row][column].to_digit(10) { - None => { continue }, - Some(idx) => {if table[idx as usize] > 0 { return false } else { table[idx as usize] = 1 }}, + None => continue, + Some(idx) => { + if table[idx as usize] > 0 { + return false; + } else { + table[idx as usize] = 1 + } + } } } } @@ -113,31 +137,33 @@ mod tests { #[test] fn test_36() { - assert_eq!(Solution::is_valid_sudoku( - vec![ - vec!['8','3','.','.','7','.','.','.','.'], - vec!['6','.','.','1','9','5','.','.','.'], - vec!['.','9','8','.','.','.','.','6','.'], - vec!['8','.','.','.','6','.','.','.','3'], - vec!['4','.','.','8','.','3','.','.','1'], - vec!['7','.','.','.','2','.','.','.','6'], - vec!['.','6','.','.','.','.','2','8','.'], - vec!['.','.','.','4','1','9','.','.','5'], - vec!['.','.','.','.','8','.','.','7','9'], - ] - ), false); - assert_eq!(Solution::is_valid_sudoku( - vec![ - vec!['5','3','.','.','7','.','.','.','.'], - vec!['6','.','.','1','9','5','.','.','.'], - vec!['.','9','8','.','.','.','.','6','.'], - vec!['8','.','.','.','6','.','.','.','3'], - vec!['4','.','.','8','.','3','.','.','1'], - vec!['7','.','.','.','2','.','.','.','6'], - vec!['.','6','.','.','.','.','2','8','.'], - vec!['.','.','.','4','1','9','.','.','5'], - vec!['.','.','.','.','8','.','.','7','9'] - ] - ), true); + assert_eq!( + Solution::is_valid_sudoku(vec![ + vec!['8', '3', '.', '.', '7', '.', '.', '.', '.'], + vec!['6', '.', '.', '1', '9', '5', '.', '.', '.'], + vec!['.', '9', '8', '.', '.', '.', '.', '6', '.'], + vec!['8', '.', '.', '.', '6', '.', '.', '.', '3'], + vec!['4', '.', '.', '8', '.', '3', '.', '.', '1'], + vec!['7', '.', '.', '.', '2', '.', '.', '.', '6'], + vec!['.', '6', '.', '.', '.', '.', '2', '8', '.'], + vec!['.', '.', '.', '4', '1', '9', '.', '.', '5'], + vec!['.', '.', '.', '.', '8', '.', '.', '7', '9'], + ]), + false + ); + assert_eq!( + Solution::is_valid_sudoku(vec![ + vec!['5', '3', '.', '.', '7', '.', '.', '.', '.'], + vec!['6', '.', '.', '1', '9', '5', '.', '.', '.'], + vec!['.', '9', '8', '.', '.', '.', '.', '6', '.'], + vec!['8', '.', '.', '.', '6', '.', '.', '.', '3'], + vec!['4', '.', '.', '8', '.', '3', '.', '.', '1'], + vec!['7', '.', '.', '.', '2', '.', '.', '.', '6'], + vec!['.', '6', '.', '.', '.', '.', '2', '8', '.'], + vec!['.', '.', '.', '4', '1', '9', '.', '.', '5'], + vec!['.', '.', '.', '.', '8', '.', '.', '7', '9'] + ]), + true + ); } } diff --git a/src/n0037_sudoku_solver.rs b/src/n0037_sudoku_solver.rs index 245050a3..a848d26c 100644 --- a/src/n0037_sudoku_solver.rs +++ b/src/n0037_sudoku_solver.rs @@ -2,31 +2,31 @@ * [37] Sudoku Solver * * Write a program to solve a Sudoku puzzle by filling the empty cells. - * + * * A sudoku solution must satisfy all of the following rules: - * + * *
    * Each of the digits 1-9 must occur exactly once in each row. * Each of the digits 1-9 must occur exactly once in each column. * Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. *
- * + * * Empty cells are indicated by the character '.'. - * + * *
* A sudoku puzzle... - * + * *
* ...and its solution numbers marked in red. - * + * * Note: - * - * + * + * * The given board contain only digits 1-9 and the character '.'. * You may assume that the given Sudoku puzzle will have a single unique solution. * The given board size is always 9x9. - * - * + * + * */ pub struct Solution {} @@ -34,9 +34,7 @@ pub struct Solution {} // TODO impl Solution { - pub fn solve_sudoku(board: &mut Vec>) { - - } + pub fn solve_sudoku(board: &mut Vec>) {} } // submission codes end @@ -46,6 +44,5 @@ mod tests { use super::*; #[test] - fn test_37() { - } + fn test_37() {} } diff --git a/src/n0038_count_and_say.rs b/src/n0038_count_and_say.rs index 08e48633..53d1c269 100644 --- a/src/n0038_count_and_say.rs +++ b/src/n0038_count_and_say.rs @@ -2,38 +2,38 @@ * [38] Count and Say * * The count-and-say sequence is the sequence of integers with the first five terms as following: - * - * + * + * * 1. 1 * 2. 11 * 3. 21 * 4. 1211 * 5. 111221 - * - * + * + * * 1 is read off as "one 1" or 11.
* 11 is read off as "two 1s" or 21.
* 21 is read off as "one 2, then one 1" or 1211. * * Given an integer n where 1 <= n <= 30, generate the n^th term of the count-and-say sequence. - * + * * Note: Each term of the sequence of integers will be represented as a string. - * + * * - * + * * Example 1: - * - * + * + * * Input: 1 * Output: "1" - * - * + * + * * Example 2: - * - * + * + * * Input: 4 * Output: "1211" - * + * */ pub struct Solution {} @@ -43,7 +43,7 @@ use std::char::from_digit; impl Solution { pub fn count_and_say(n: i32) -> String { let mut res = vec!['1']; - for _ in 0..n-1 { + for _ in 0..n - 1 { let mut temp = Vec::new(); let mut i = 0_usize; while i < res.len() { diff --git a/src/n0039_combination_sum.rs b/src/n0039_combination_sum.rs index 94c10dd3..e589e9a7 100644 --- a/src/n0039_combination_sum.rs +++ b/src/n0039_combination_sum.rs @@ -2,30 +2,30 @@ * [39] Combination Sum * * Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. - * + * * The same repeated number may be chosen from candidates unlimited number of times. - * + * * Note: - * - * + * + * * All numbers (including target) will be positive integers. * The solution set must not contain duplicate combinations. - * - * + * + * * Example 1: - * - * + * + * * Input: candidates = [2,3,6,7], target = 7, * A solution set is: * [ * [7], * [2,2,3] * ] - * - * + * + * * Example 2: - * - * + * + * * Input: candidates = [2,3,5], target = 8, * A solution set is: * [ @@ -33,8 +33,8 @@ * [2,3,3], * [3,5] * ] - * - * + * + * */ pub struct Solution {} @@ -44,21 +44,29 @@ impl Solution { pub fn combination_sum(candidates: Vec, target: i32) -> Vec> { let mut seq = candidates; let mut res = Vec::new(); - seq.sort_unstable_by(|a, b| { b.cmp(a) }); + seq.sort_unstable_by(|a, b| b.cmp(a)); let mut vec = Vec::new(); Solution::backtrack(&seq, target, vec, &mut res, 0); res } - fn backtrack(seq: &Vec, target: i32, mut curr: Vec, result: &mut Vec>, start_idx: usize) { + fn backtrack( + seq: &Vec, + target: i32, + mut curr: Vec, + result: &mut Vec>, + start_idx: usize, + ) { for i in start_idx..seq.len() { let item = seq[i]; - if target - item < 0 { continue } + if target - item < 0 { + continue; + } let mut new_vec = curr.clone(); new_vec.push(item); if target == item { result.push(new_vec); - } else { + } else { Solution::backtrack(seq, target - item, new_vec, result, i); } } @@ -73,17 +81,17 @@ mod tests { #[test] fn test_39() { - assert_eq!(Solution::combination_sum(vec![1], 7), vec![vec![1,1,1,1,1,1,1]]); - assert_eq!(Solution::combination_sum(vec![2,3,6,7], 7), - vec![ - vec![7], - vec![3,2,2], - ]); - assert_eq!(Solution::combination_sum(vec![2,3,5], 8), - vec![ - vec![5,3], - vec![3,3,2], - vec![2,2,2,2], - ]); + assert_eq!( + Solution::combination_sum(vec![1], 7), + vec![vec![1, 1, 1, 1, 1, 1, 1]] + ); + assert_eq!( + Solution::combination_sum(vec![2, 3, 6, 7], 7), + vec![vec![7], vec![3, 2, 2],] + ); + assert_eq!( + Solution::combination_sum(vec![2, 3, 5], 8), + vec![vec![5, 3], vec![3, 3, 2], vec![2, 2, 2, 2],] + ); } } diff --git a/src/n0041_first_missing_positive.rs b/src/n0041_first_missing_positive.rs index 210d8b9c..72642eb2 100644 --- a/src/n0041_first_missing_positive.rs +++ b/src/n0041_first_missing_positive.rs @@ -2,32 +2,32 @@ * [41] First Missing Positive * * Given an unsorted integer array, find the smallest missing positive integer. - * + * * Example 1: - * - * + * + * * Input: [1,2,0] * Output: 3 - * - * + * + * * Example 2: - * - * + * + * * Input: [3,4,-1,1] * Output: 2 - * - * + * + * * Example 3: - * - * + * + * * Input: [7,8,9,11,12] * Output: 1 - * - * + * + * * Note: - * + * * Your algorithm should run in O(n) time and uses constant extra space. - * + * */ pub struct Solution {} @@ -53,10 +53,10 @@ impl Solution { println!("{}", c); for (i, &num) in nums.iter().enumerate() { if num != ((i + 1) as i32) { - return (i+1) as i32 + return (i + 1) as i32; } } - return (len + 1) as i32 + return (len + 1) as i32; } } @@ -68,12 +68,21 @@ mod tests { #[test] fn test_41() { - assert_eq!(Solution::first_missing_positive(vec![2,2]), 1); - assert_eq!(Solution::first_missing_positive(vec![12,11,10,9,8,7,6,5,4,3,2]), 1); - assert_eq!(Solution::first_missing_positive(vec![2,2,2,2,2,2,2]), 1); - assert_eq!(Solution::first_missing_positive(vec![3,4,-1,1]), 2); - assert_eq!(Solution::first_missing_positive(vec![2,1,0]), 3); - assert_eq!(Solution::first_missing_positive(vec![7,8,9,11,12]), 1); - assert_eq!(Solution::first_missing_positive(vec![7,8,1,2,3,3,3,3,3,3,3,-5,-7,1234]), 4); + assert_eq!(Solution::first_missing_positive(vec![2, 2]), 1); + assert_eq!( + Solution::first_missing_positive(vec![12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2]), + 1 + ); + assert_eq!( + Solution::first_missing_positive(vec![2, 2, 2, 2, 2, 2, 2]), + 1 + ); + assert_eq!(Solution::first_missing_positive(vec![3, 4, -1, 1]), 2); + assert_eq!(Solution::first_missing_positive(vec![2, 1, 0]), 3); + assert_eq!(Solution::first_missing_positive(vec![7, 8, 9, 11, 12]), 1); + assert_eq!( + Solution::first_missing_positive(vec![7, 8, 1, 2, 3, 3, 3, 3, 3, 3, 3, -5, -7, 1234]), + 4 + ); } } diff --git a/src/n0042_trapping_rain_water.rs b/src/n0042_trapping_rain_water.rs index 02fce508..d60647dd 100644 --- a/src/n0042_trapping_rain_water.rs +++ b/src/n0042_trapping_rain_water.rs @@ -2,16 +2,16 @@ * [42] Trapping Rain Water * * Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. - * + * *
* The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! - * + * * Example: - * - * + * + * * Input: [0,1,0,2,1,0,1,3,2,1,2,1] * Output: 6 - * + * */ pub struct Solution {} @@ -31,6 +31,5 @@ mod tests { use super::*; #[test] - fn test_42() { - } + fn test_42() {} } diff --git a/src/n0043_multiply_strings.rs b/src/n0043_multiply_strings.rs index 93c6e636..a2400d6c 100644 --- a/src/n0043_multiply_strings.rs +++ b/src/n0043_multiply_strings.rs @@ -2,37 +2,37 @@ * [43] Multiply Strings * * Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. - * + * * Example 1: - * - * + * + * * Input: num1 = "2", num2 = "3" * Output: "6" - * + * * Example 2: - * - * + * + * * Input: num1 = "123", num2 = "456" * Output: "56088" - * - * + * + * * Note: - * + * *
    * The length of both num1 and num2 is < 110. * Both num1 and num2 contain only digits 0-9. * Both num1 and num2 do not contain any leading zero, except the number 0 itself. * You must not use any built-in BigInteger library or convert the inputs to integer directly. *
- * + * */ pub struct Solution {} // submission codes start here // TODO -use std::collections::VecDeque; use std::char::from_digit; +use std::collections::VecDeque; impl Solution { pub fn multiply(num1: String, num2: String) -> String { let mut num1: Vec = num1.chars().map(|ch| ch.to_digit(10).unwrap()).collect(); @@ -43,10 +43,10 @@ impl Solution { num1.reverse(); num2.reverse(); for (i, multiplier) in num1.into_iter().enumerate() { - buffer.pop_back().and_then(|digit| - Some(res.push(from_digit(digit, 10).unwrap()))); - for &multiplicand in num2.iter() { - } + buffer + .pop_back() + .and_then(|digit| Some(res.push(from_digit(digit, 10).unwrap()))); + for &multiplicand in num2.iter() {} } res.reverse(); res.into_iter().collect() @@ -60,6 +60,5 @@ mod tests { use super::*; #[test] - fn test_43() { - } + fn test_43() {} } diff --git a/src/n0044_wildcard_matching.rs b/src/n0044_wildcard_matching.rs index 26fba8f1..c4156c36 100644 --- a/src/n0044_wildcard_matching.rs +++ b/src/n0044_wildcard_matching.rs @@ -2,70 +2,70 @@ * [44] Wildcard Matching * * Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. - * - * + * + * * '?' Matches any single character. * '*' Matches any sequence of characters (including the empty sequence). - * - * + * + * * The matching should cover the entire input string (not partial). - * + * * Note: - * - * + * + * * s could be empty and contains only lowercase letters a-z. * p could be empty and contains only lowercase letters a-z, and characters like ? or *. - * - * + * + * * Example 1: - * - * + * + * * Input: * s = "aa" * p = "a" * Output: false * Explanation: "a" does not match the entire string "aa". - * - * + * + * * Example 2: - * - * + * + * * Input: * s = "aa" * p = "*" * Output: true * Explanation: '*' matches any sequence. - * - * + * + * * Example 3: - * - * + * + * * Input: * s = "cb" * p = "?a" * Output: false * Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. - * - * + * + * * Example 4: - * - * + * + * * Input: * s = "adceb" * p = "*a*b" * Output: true * Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". - * - * + * + * * Example 5: - * - * + * + * * Input: * s = "acdcb" * p = "a*c?b" * Output: false - * - * + * + * */ pub struct Solution {} @@ -84,6 +84,5 @@ mod tests { use super::*; #[test] - fn test_44() { - } + fn test_44() {} } diff --git a/src/n0045_jump_game_ii.rs b/src/n0045_jump_game_ii.rs index 822d1b41..1f2de2aa 100644 --- a/src/n0045_jump_game_ii.rs +++ b/src/n0045_jump_game_ii.rs @@ -2,23 +2,23 @@ * [45] Jump Game II * * Given an array of non-negative integers, you are initially positioned at the first index of the array. - * + * * Each element in the array represents your maximum jump length at that position. - * + * * Your goal is to reach the last index in the minimum number of jumps. - * + * * Example: - * - * + * + * * Input: [2,3,1,1,4] * Output: 2 * Explanation: The minimum number of jumps to reach the last index is 2. * Jump 1 step from index 0 to 1, then 3 steps to the last index. - * + * * Note: - * + * * You can assume that you can always reach the last index. - * + * */ pub struct Solution {} @@ -38,6 +38,5 @@ mod tests { use super::*; #[test] - fn test_45() { - } + fn test_45() {} } diff --git a/src/n0046_permutations.rs b/src/n0046_permutations.rs index 0a697d8f..a6cdb8dd 100644 --- a/src/n0046_permutations.rs +++ b/src/n0046_permutations.rs @@ -2,10 +2,10 @@ * [46] Permutations * * Given a collection of distinct integers, return all possible permutations. - * + * * Example: - * - * + * + * * Input: [1,2,3] * Output: * [ @@ -16,8 +16,8 @@ * [3,1,2], * [3,2,1] * ] - * - * + * + * */ pub struct Solution {} @@ -25,13 +25,22 @@ pub struct Solution {} impl Solution { pub fn permute(nums: Vec) -> Vec> { - if nums.len() <= 1 { return vec![nums] } - nums.iter().flat_map(|&num| { - let mut sub = nums.clone().into_iter().filter(|&x| x != num).collect(); - Solution::permute(sub).into_iter().map(|vec| { - let mut vec = vec; vec.push(num); vec - }).collect::>>() - }).collect() + if nums.len() <= 1 { + return vec![nums]; + } + nums.iter() + .flat_map(|&num| { + let mut sub = nums.clone().into_iter().filter(|&x| x != num).collect(); + Solution::permute(sub) + .into_iter() + .map(|vec| { + let mut vec = vec; + vec.push(num); + vec + }) + .collect::>>() + }) + .collect() } } @@ -44,14 +53,14 @@ mod tests { #[test] fn test_46() { assert_eq!( - Solution::permute(vec![1,2,3]), + Solution::permute(vec![1, 2, 3]), vec![ - vec![3,2,1], - vec![2,3,1], - vec![3,1,2], - vec![1,3,2], - vec![2,1,3], - vec![1,2,3], + vec![3, 2, 1], + vec![2, 3, 1], + vec![3, 1, 2], + vec![1, 3, 2], + vec![2, 1, 3], + vec![1, 2, 3], ] ) } diff --git a/src/n0047_permutations_ii.rs b/src/n0047_permutations_ii.rs index 79ee81c4..22aef579 100644 --- a/src/n0047_permutations_ii.rs +++ b/src/n0047_permutations_ii.rs @@ -2,10 +2,10 @@ * [47] Permutations II * * Given a collection of numbers that might contain duplicates, return all possible unique permutations. - * + * * Example: - * - * + * + * * Input: [1,1,2] * Output: * [ @@ -13,8 +13,8 @@ * [1,2,1], * [2,1,1] * ] - * - * + * + * */ pub struct Solution {} @@ -28,16 +28,27 @@ impl Solution { } fn permute(mut nums: Vec) -> Vec> { - if nums.len() <= 1 { return vec![nums]} + if nums.len() <= 1 { + return vec![nums]; + } let mut prev: Option = None; let mut res = Vec::new(); for (i, &num) in nums.iter().enumerate() { - if prev.is_some() && prev.unwrap() == num { continue } else { prev = Some(num) } + if prev.is_some() && prev.unwrap() == num { + continue; + } else { + prev = Some(num) + } let mut sub = nums.clone(); sub.remove(i); - let mut permutations: Vec> = Solution::permute(sub).into_iter().map(|x| { - let mut x = x; x.push(num); x - }).collect(); + let mut permutations: Vec> = Solution::permute(sub) + .into_iter() + .map(|x| { + let mut x = x; + x.push(num); + x + }) + .collect(); res.append(&mut permutations); } res @@ -53,120 +64,113 @@ mod tests { #[test] fn test_47() { assert_eq!( - Solution::permute(vec![1,1,2]), - vec![ - vec![2,1,1], - vec![1,2,1], - vec![1,1,2], - ] + Solution::permute(vec![1, 1, 2]), + vec![vec![2, 1, 1], vec![1, 2, 1], vec![1, 1, 2],] ); + assert_eq!(Solution::permute(vec![1, 1, 1]), vec![vec![1, 1, 1],]); assert_eq!( - Solution::permute(vec![1,1,1]), + Solution::permute(vec![1, 1, 1, 2]), vec![ - vec![1,1,1], + vec![2, 1, 1, 1], + vec![1, 2, 1, 1], + vec![1, 1, 2, 1], + vec![1, 1, 1, 2], ] ); assert_eq!( - Solution::permute(vec![1,1,1,2]), + Solution::permute(vec![1, 1, 2, 2, 3, 3]), vec![ - vec![2,1,1,1], - vec![1,2,1,1], - vec![1,1,2,1], - vec![1,1,1,2], + vec![3, 3, 2, 2, 1, 1], + vec![3, 2, 3, 2, 1, 1], + vec![2, 3, 3, 2, 1, 1], + vec![3, 2, 2, 3, 1, 1], + vec![2, 3, 2, 3, 1, 1], + vec![2, 2, 3, 3, 1, 1], + vec![3, 3, 2, 1, 2, 1], + vec![3, 2, 3, 1, 2, 1], + vec![2, 3, 3, 1, 2, 1], + vec![3, 3, 1, 2, 2, 1], + vec![3, 1, 3, 2, 2, 1], + vec![1, 3, 3, 2, 2, 1], + vec![3, 2, 1, 3, 2, 1], + vec![2, 3, 1, 3, 2, 1], + vec![3, 1, 2, 3, 2, 1], + vec![1, 3, 2, 3, 2, 1], + vec![2, 1, 3, 3, 2, 1], + vec![1, 2, 3, 3, 2, 1], + vec![3, 2, 2, 1, 3, 1], + vec![2, 3, 2, 1, 3, 1], + vec![2, 2, 3, 1, 3, 1], + vec![3, 2, 1, 2, 3, 1], + vec![2, 3, 1, 2, 3, 1], + vec![3, 1, 2, 2, 3, 1], + vec![1, 3, 2, 2, 3, 1], + vec![2, 1, 3, 2, 3, 1], + vec![1, 2, 3, 2, 3, 1], + vec![2, 2, 1, 3, 3, 1], + vec![2, 1, 2, 3, 3, 1], + vec![1, 2, 2, 3, 3, 1], + vec![3, 3, 2, 1, 1, 2], + vec![3, 2, 3, 1, 1, 2], + vec![2, 3, 3, 1, 1, 2], + vec![3, 3, 1, 2, 1, 2], + vec![3, 1, 3, 2, 1, 2], + vec![1, 3, 3, 2, 1, 2], + vec![3, 2, 1, 3, 1, 2], + vec![2, 3, 1, 3, 1, 2], + vec![3, 1, 2, 3, 1, 2], + vec![1, 3, 2, 3, 1, 2], + vec![2, 1, 3, 3, 1, 2], + vec![1, 2, 3, 3, 1, 2], + vec![3, 3, 1, 1, 2, 2], + vec![3, 1, 3, 1, 2, 2], + vec![1, 3, 3, 1, 2, 2], + vec![3, 1, 1, 3, 2, 2], + vec![1, 3, 1, 3, 2, 2], + vec![1, 1, 3, 3, 2, 2], + vec![3, 2, 1, 1, 3, 2], + vec![2, 3, 1, 1, 3, 2], + vec![3, 1, 2, 1, 3, 2], + vec![1, 3, 2, 1, 3, 2], + vec![2, 1, 3, 1, 3, 2], + vec![1, 2, 3, 1, 3, 2], + vec![3, 1, 1, 2, 3, 2], + vec![1, 3, 1, 2, 3, 2], + vec![1, 1, 3, 2, 3, 2], + vec![2, 1, 1, 3, 3, 2], + vec![1, 2, 1, 3, 3, 2], + vec![1, 1, 2, 3, 3, 2], + vec![3, 2, 2, 1, 1, 3], + vec![2, 3, 2, 1, 1, 3], + vec![2, 2, 3, 1, 1, 3], + vec![3, 2, 1, 2, 1, 3], + vec![2, 3, 1, 2, 1, 3], + vec![3, 1, 2, 2, 1, 3], + vec![1, 3, 2, 2, 1, 3], + vec![2, 1, 3, 2, 1, 3], + vec![1, 2, 3, 2, 1, 3], + vec![2, 2, 1, 3, 1, 3], + vec![2, 1, 2, 3, 1, 3], + vec![1, 2, 2, 3, 1, 3], + vec![3, 2, 1, 1, 2, 3], + vec![2, 3, 1, 1, 2, 3], + vec![3, 1, 2, 1, 2, 3], + vec![1, 3, 2, 1, 2, 3], + vec![2, 1, 3, 1, 2, 3], + vec![1, 2, 3, 1, 2, 3], + vec![3, 1, 1, 2, 2, 3], + vec![1, 3, 1, 2, 2, 3], + vec![1, 1, 3, 2, 2, 3], + vec![2, 1, 1, 3, 2, 3], + vec![1, 2, 1, 3, 2, 3], + vec![1, 1, 2, 3, 2, 3], + vec![2, 2, 1, 1, 3, 3], + vec![2, 1, 2, 1, 3, 3], + vec![1, 2, 2, 1, 3, 3], + vec![2, 1, 1, 2, 3, 3], + vec![1, 2, 1, 2, 3, 3], + vec![1, 1, 2, 2, 3, 3] ] ); - assert_eq!( - Solution::permute(vec![1,1,2,2,3,3]), - vec![vec![3, 3, 2, 2, 1, 1], - vec![3, 2, 3, 2, 1, 1], - vec![2, 3, 3, 2, 1, 1], - vec![3, 2, 2, 3, 1, 1], - vec![2, 3, 2, 3, 1, 1], - vec![2, 2, 3, 3, 1, 1], - vec![3, 3, 2, 1, 2, 1], - vec![3, 2, 3, 1, 2, 1], - vec![2, 3, 3, 1, 2, 1], - vec![3, 3, 1, 2, 2, 1], - vec![3, 1, 3, 2, 2, 1], - vec![1, 3, 3, 2, 2, 1], - vec![3, 2, 1, 3, 2, 1], - vec![2, 3, 1, 3, 2, 1], - vec![3, 1, 2, 3, 2, 1], - vec![1, 3, 2, 3, 2, 1], - vec![2, 1, 3, 3, 2, 1], - vec![1, 2, 3, 3, 2, 1], - vec![3, 2, 2, 1, 3, 1], - vec![2, 3, 2, 1, 3, 1], - vec![2, 2, 3, 1, 3, 1], - vec![3, 2, 1, 2, 3, 1], - vec![2, 3, 1, 2, 3, 1], - vec![3, 1, 2, 2, 3, 1], - vec![1, 3, 2, 2, 3, 1], - vec![2, 1, 3, 2, 3, 1], - vec![1, 2, 3, 2, 3, 1], - vec![2, 2, 1, 3, 3, 1], - vec![2, 1, 2, 3, 3, 1], - vec![1, 2, 2, 3, 3, 1], - vec![3, 3, 2, 1, 1, 2], - vec![3, 2, 3, 1, 1, 2], - vec![2, 3, 3, 1, 1, 2], - vec![3, 3, 1, 2, 1, 2], - vec![3, 1, 3, 2, 1, 2], - vec![1, 3, 3, 2, 1, 2], - vec![3, 2, 1, 3, 1, 2], - vec![2, 3, 1, 3, 1, 2], - vec![3, 1, 2, 3, 1, 2], - vec![1, 3, 2, 3, 1, 2], - vec![2, 1, 3, 3, 1, 2], - vec![1, 2, 3, 3, 1, 2], - vec![3, 3, 1, 1, 2, 2], - vec![3, 1, 3, 1, 2, 2], - vec![1, 3, 3, 1, 2, 2], - vec![3, 1, 1, 3, 2, 2], - vec![1, 3, 1, 3, 2, 2], - vec![1, 1, 3, 3, 2, 2], - vec![3, 2, 1, 1, 3, 2], - vec![2, 3, 1, 1, 3, 2], - vec![3, 1, 2, 1, 3, 2], - vec![1, 3, 2, 1, 3, 2], - vec![2, 1, 3, 1, 3, 2], - vec![1, 2, 3, 1, 3, 2], - vec![3, 1, 1, 2, 3, 2], - vec![1, 3, 1, 2, 3, 2], - vec![1, 1, 3, 2, 3, 2], - vec![2, 1, 1, 3, 3, 2], - vec![1, 2, 1, 3, 3, 2], - vec![1, 1, 2, 3, 3, 2], - vec![3, 2, 2, 1, 1, 3], - vec![2, 3, 2, 1, 1, 3], - vec![2, 2, 3, 1, 1, 3], - vec![3, 2, 1, 2, 1, 3], - vec![2, 3, 1, 2, 1, 3], - vec![3, 1, 2, 2, 1, 3], - vec![1, 3, 2, 2, 1, 3], - vec![2, 1, 3, 2, 1, 3], - vec![1, 2, 3, 2, 1, 3], - vec![2, 2, 1, 3, 1, 3], - vec![2, 1, 2, 3, 1, 3], - vec![1, 2, 2, 3, 1, 3], - vec![3, 2, 1, 1, 2, 3], - vec![2, 3, 1, 1, 2, 3], - vec![3, 1, 2, 1, 2, 3], - vec![1, 3, 2, 1, 2, 3], - vec![2, 1, 3, 1, 2, 3], - vec![1, 2, 3, 1, 2, 3], - vec![3, 1, 1, 2, 2, 3], - vec![1, 3, 1, 2, 2, 3], - vec![1, 1, 3, 2, 2, 3], - vec![2, 1, 1, 3, 2, 3], - vec![1, 2, 1, 3, 2, 3], - vec![1, 1, 2, 3, 2, 3], - vec![2, 2, 1, 1, 3, 3], - vec![2, 1, 2, 1, 3, 3], - vec![1, 2, 2, 1, 3, 3], - vec![2, 1, 1, 2, 3, 3], - vec![1, 2, 1, 2, 3, 3], - vec![1, 1, 2, 2, 3, 3]] - ); } } diff --git a/src/n0048_rotate_image.rs b/src/n0048_rotate_image.rs index e2c9be0a..01145b47 100644 --- a/src/n0048_rotate_image.rs +++ b/src/n0048_rotate_image.rs @@ -2,42 +2,42 @@ * [48] Rotate Image * * You are given an n x n 2D matrix representing an image. - * + * * Rotate the image by 90 degrees (clockwise). - * + * * Note: - * + * * You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. - * + * * Example 1: - * - * - * Given input matrix = + * + * + * Given input matrix = * [ * [1,2,3], * [4,5,6], * [7,8,9] * ], - * + * * rotate the input matrix in-place such that it becomes: * [ * [7,4,1], * [8,5,2], * [9,6,3] * ] - * - * + * + * * Example 2: - * - * + * + * * Given input matrix = * [ * [ 5, 1, 9,11], * [ 2, 4, 8,10], * [13, 3, 6, 7], * [15,14,12,16] - * ], - * + * ], + * * rotate the input matrix in-place such that it becomes: * [ * [15,13, 2, 5], @@ -45,8 +45,8 @@ * [12, 6, 8, 9], * [16, 7,10,11] * ] - * - * + * + * */ pub struct Solution {} @@ -78,14 +78,14 @@ pub struct Solution {} impl Solution { pub fn rotate(matrix: &mut Vec>) { let mut matrix = matrix; - let (len, n) = (matrix.len(), matrix.len()-1); - for x in 0..len/2 { - for y in 0..(len+1)/2 { + let (len, n) = (matrix.len(), matrix.len() - 1); + for x in 0..len / 2 { + for y in 0..(len + 1) / 2 { let temp = matrix[x][y]; - matrix[x][y] = matrix[n-y][x]; - matrix[n-y][x] = matrix[n-x][n-y]; - matrix[n-x][n-y] = matrix[y][n-x]; - matrix[y][n-x] = temp; + matrix[x][y] = matrix[n - y][x]; + matrix[n - y][x] = matrix[n - x][n - y]; + matrix[n - x][n - y] = matrix[y][n - x]; + matrix[y][n - x] = temp; } } } @@ -99,19 +99,21 @@ mod tests { #[test] fn test_48() { - let mut matrix = - vec![ - vec![ 5, 1, 9,11], - vec![ 2, 4, 8,10], - vec![13, 3, 6, 7], - vec![15,14,12,16]]; + let mut matrix = vec![ + vec![5, 1, 9, 11], + vec![2, 4, 8, 10], + vec![13, 3, 6, 7], + vec![15, 14, 12, 16], + ]; Solution::rotate(&mut matrix); - assert_eq!(matrix, - vec![ - vec![15,13, 2, 5], - vec![14, 3, 4, 1], - vec![12, 6, 8, 9], - vec![16, 7,10,11] - ]); + assert_eq!( + matrix, + vec![ + vec![15, 13, 2, 5], + vec![14, 3, 4, 1], + vec![12, 6, 8, 9], + vec![16, 7, 10, 11] + ] + ); } } diff --git a/src/n0049_group_anagrams.rs b/src/n0049_group_anagrams.rs index adf27bb1..737dc03b 100644 --- a/src/n0049_group_anagrams.rs +++ b/src/n0049_group_anagrams.rs @@ -2,10 +2,10 @@ * [49] Group Anagrams * * Given an array of strings, group anagrams together. - * + * * Example: - * - * + * + * * Input: ["eat", "tea", "tan", "ate", "nat", "bat"], * Output: * [ @@ -13,14 +13,14 @@ * ["nat","tan"], * ["bat"] * ] - * + * * Note: - * - * + * + * * All inputs will be in lowercase. * The order of your output does not matter. - * - * + * + * */ pub struct Solution {} @@ -52,11 +52,13 @@ mod tests { #[test] #[ignore] fn test_49() { - assert_eq!(Solution::group_anagrams(vec_string!["eat", "tea", "tan", "ate", "nat", "bat"]), - vec![ - vec_string!["tan","nat"], - vec_string!["bat"], - vec_string!["eat","ate","tea"], - ]); + assert_eq!( + Solution::group_anagrams(vec_string!["eat", "tea", "tan", "ate", "nat", "bat"]), + vec![ + vec_string!["tan", "nat"], + vec_string!["bat"], + vec_string!["eat", "ate", "tea"], + ] + ); } } diff --git a/src/n0050_powx_n.rs b/src/n0050_powx_n.rs index 97b7c582..6e89f90c 100644 --- a/src/n0050_powx_n.rs +++ b/src/n0050_powx_n.rs @@ -2,36 +2,36 @@ * [50] Pow(x, n) * * Implement pow(x, n), which calculates x raised to the power n (x^n). - * + * * Example 1: - * - * + * + * * Input: 2.00000, 10 * Output: 1024.00000 - * - * + * + * * Example 2: - * - * + * + * * Input: 2.10000, 3 * Output: 9.26100 - * - * + * + * * Example 3: - * - * + * + * * Input: 2.00000, -2 * Output: 0.25000 * Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25 - * - * + * + * * Note: - * - * + * + * * -100.0 < x < 100.0 * n is a 32-bit signed integer, within the range [-2^31, 2^31 - 1] - * - * + * + * */ pub struct Solution {} diff --git a/src/n0051_n_queens.rs b/src/n0051_n_queens.rs index 7871c86c..98fd9480 100644 --- a/src/n0051_n_queens.rs +++ b/src/n0051_n_queens.rs @@ -2,31 +2,31 @@ * [51] N-Queens * * The n-queens puzzle is the problem of placing n queens on an n*n chessboard such that no two queens attack each other. - * + * * - * + * * Given an integer n, return all distinct solutions to the n-queens puzzle. - * + * * Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. - * + * * Example: - * - * + * + * * Input: 4 * Output: [ * [".Q..", // Solution 1 * "...Q", * "Q...", * "..Q."], - * + * * ["..Q.", // Solution 2 * "Q...", * "...Q", * ".Q.."] * ] * Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above. - * - * + * + * */ pub struct Solution {} @@ -40,16 +40,19 @@ impl Solution { solution } - fn schedule_queens(board: &mut Vec>, - solution: &mut Vec>, - len: usize, row: usize) { + fn schedule_queens( + board: &mut Vec>, + solution: &mut Vec>, + len: usize, + row: usize, + ) { for col in 0..len { if !Solution::collision(&board, len, row, col) { board[row][col] = 'Q'; if row == len - 1 { solution.push(board.iter().map(|vec| vec.iter().collect()).collect()); } else { - Solution::schedule_queens(board, solution, len, row+1); + Solution::schedule_queens(board, solution, len, row + 1); } board[row][col] = '.'; } @@ -59,17 +62,25 @@ impl Solution { #[inline(always)] fn collision(board: &Vec>, len: usize, x: usize, y: usize) -> bool { for i in 0..x { - if board[i][y] == 'Q' { return true } + if board[i][y] == 'Q' { + return true; + } } let (mut i, mut j) = (x as i32 - 1, y as i32 - 1); while i >= 0 && j >= 0 { - if board[i as usize][j as usize] == 'Q' { return true } - i -= 1; j -= 1; + if board[i as usize][j as usize] == 'Q' { + return true; + } + i -= 1; + j -= 1; } let (mut i, mut j) = (x as i32 - 1, y as i32 + 1); while i >= 0 && j < len as i32 { - if board[i as usize][j as usize] == 'Q' { return true} - i -= 1; j += 1; + if board[i as usize][j as usize] == 'Q' { + return true; + } + i -= 1; + j += 1; } false } @@ -86,20 +97,10 @@ mod tests { assert_eq!( Solution::solve_n_queens(4), vec![ - vec![".Q..", - "...Q", - "Q...", - "..Q."], - - vec!["..Q.", - "Q...", - "...Q", - ".Q.."] + vec![".Q..", "...Q", "Q...", "..Q."], + vec!["..Q.", "Q...", "...Q", ".Q.."] ] ); - assert_eq!( - Solution::solve_n_queens(8).len(), - 92 - ); + assert_eq!(Solution::solve_n_queens(8).len(), 92); } } diff --git a/src/n0052_n_queens_ii.rs b/src/n0052_n_queens_ii.rs index 27c29044..873cdda5 100644 --- a/src/n0052_n_queens_ii.rs +++ b/src/n0052_n_queens_ii.rs @@ -2,14 +2,14 @@ * [52] N-Queens II * * The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. - * + * * - * + * * Given an integer n, return the number of distinct solutions to the n-queens puzzle. - * + * * Example: - * - * + * + * * Input: 4 * Output: 2 * Explanation: There are two distinct solutions to the 4-queens puzzle as shown below. @@ -18,14 +18,14 @@ * "...Q", * "Q...", * "..Q."], - * + * * ["..Q.", // Solution 2 * "Q...", * "...Q", * ".Q.."] * ] - * - * + * + * */ pub struct Solution {} @@ -39,16 +39,14 @@ impl Solution { num } - fn schedule_queens(board: &mut Vec>, - num: &mut i32, - len: usize, row: usize) { + fn schedule_queens(board: &mut Vec>, num: &mut i32, len: usize, row: usize) { for col in 0..len { if !Solution::collision(&board, len, row, col) { board[row][col] = 'Q'; if row == len - 1 { *num += 1; } else { - Solution::schedule_queens(board, num, len, row+1); + Solution::schedule_queens(board, num, len, row + 1); } board[row][col] = '.'; } @@ -58,17 +56,23 @@ impl Solution { #[inline(always)] fn collision(board: &Vec>, len: usize, x: usize, y: usize) -> bool { for i in 0..x { - if board[i][y] == 'Q' { return true } + if board[i][y] == 'Q' { + return true; + } } let (mut i, mut j) = (x as i32 - 1, y as i32 - 1); while i >= 0 && j >= 0 { - if board[i as usize][j as usize] == 'Q' { return true } + if board[i as usize][j as usize] == 'Q' { + return true; + } i -= 1; j -= 1; } let (mut i, mut j) = (x as i32 - 1, y as i32 + 1); while i >= 0 && j < len as i32 { - if board[i as usize][j as usize] == 'Q' { return true } + if board[i as usize][j as usize] == 'Q' { + return true; + } i -= 1; j += 1; } diff --git a/src/n0053_maximum_subarray.rs b/src/n0053_maximum_subarray.rs index e3d25782..72b8b234 100644 --- a/src/n0053_maximum_subarray.rs +++ b/src/n0053_maximum_subarray.rs @@ -2,19 +2,19 @@ * [53] Maximum Subarray * * Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. - * + * * Example: - * - * + * + * * Input: [-2,1,-3,4,-1,2,1,-5,4], * Output: 6 * Explanation: [4,-1,2,1] has the largest sum = 6. - * - * + * + * * Follow up: - * + * * If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. - * + * */ pub struct Solution {} @@ -28,7 +28,7 @@ impl Solution { for j in 0..nums.len() { curr += nums[j]; max = i32::max(max, curr); - if curr <=0 { + if curr <= 0 { curr = 0; } } @@ -44,7 +44,10 @@ mod tests { #[test] fn test_53() { - assert_eq!(Solution::max_sub_array(vec![-2,1,-3,4,-1,2,1,-5,4]), 6); + assert_eq!( + Solution::max_sub_array(vec![-2, 1, -3, 4, -1, 2, 1, -5, 4]), + 6 + ); assert_eq!(Solution::max_sub_array(vec![-8]), -8); assert_eq!(Solution::max_sub_array(vec![-8, -2]), -2); } diff --git a/src/n0054_spiral_matrix.rs b/src/n0054_spiral_matrix.rs index b59a9d96..a2a8f009 100644 --- a/src/n0054_spiral_matrix.rs +++ b/src/n0054_spiral_matrix.rs @@ -2,10 +2,10 @@ * [54] Spiral Matrix * * Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. - * + * * Example 1: - * - * + * + * * Input: * [ * [ 1, 2, 3 ], @@ -13,10 +13,10 @@ * [ 7, 8, 9 ] * ] * Output: [1,2,3,6,9,8,7,4,5] - * - * + * + * * Example 2: - * + * * Input: * [ * [1, 2, 3, 4], @@ -24,7 +24,7 @@ * [9,10,11,12] * ] * Output: [1,2,3,4,8,12,11,10,9,5,6,7] - * + * */ pub struct Solution {} @@ -33,22 +33,40 @@ pub struct Solution {} impl Solution { pub fn spiral_order(matrix: Vec>) -> Vec { let mut res = Vec::new(); - if matrix.len() < 1 { return res } + if matrix.len() < 1 { + return res; + } let (height, width) = (matrix.len(), matrix[0].len()); let (mut x_min, mut x_max, mut y_min, mut y_max) = (0, height, 0, width); loop { - for y in y_min..y_max { res.push(matrix[x_min][y]) } + for y in y_min..y_max { + res.push(matrix[x_min][y]) + } x_min += 1; - if x_min == x_max { break } - for x in x_min..x_max { res.push(matrix[x][y_max-1]) } + if x_min == x_max { + break; + } + for x in x_min..x_max { + res.push(matrix[x][y_max - 1]) + } y_max -= 1; - if y_min == y_max { break } - for y in (y_min..y_max).rev() { res.push(matrix[x_max-1][y]) } + if y_min == y_max { + break; + } + for y in (y_min..y_max).rev() { + res.push(matrix[x_max - 1][y]) + } x_max -= 1; - if x_min == x_max { break } - for x in (x_min..x_max).rev() { res.push(matrix[x][y_min]) } + if x_min == x_max { + break; + } + for x in (x_min..x_max).rev() { + res.push(matrix[x][y_min]) + } y_min += 1; - if y_min == y_max { break } + if y_min == y_max { + break; + } } res } @@ -62,26 +80,19 @@ mod tests { #[test] fn test_54() { - assert_eq!(Solution::spiral_order(vec![ - vec![ 1, 2, 3 ], - vec![ 4, 5, 6 ], - vec![ 7, 8, 9 ] - ]), vec![1,2,3,6,9,8,7,4,5]); - assert_eq!(Solution::spiral_order(vec![ - vec![ 1, 2, 3 ] - ]), vec![1,2,3]); - assert_eq!(Solution::spiral_order(vec![ - vec![1], - vec![2], - vec![3], - ]), vec![1,2,3]); - assert_eq!(Solution::spiral_order(vec![ - vec![1], - ]), vec![1]); - assert_eq!(Solution::spiral_order(vec![ - vec![ 1, 2 ], - vec![ 4, 5 ], - ]), vec![1,2,5,4]); - + assert_eq!( + Solution::spiral_order(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]), + vec![1, 2, 3, 6, 9, 8, 7, 4, 5] + ); + assert_eq!(Solution::spiral_order(vec![vec![1, 2, 3]]), vec![1, 2, 3]); + assert_eq!( + Solution::spiral_order(vec![vec![1], vec![2], vec![3],]), + vec![1, 2, 3] + ); + assert_eq!(Solution::spiral_order(vec![vec![1],]), vec![1]); + assert_eq!( + Solution::spiral_order(vec![vec![1, 2], vec![4, 5],]), + vec![1, 2, 5, 4] + ); } } diff --git a/src/n0055_jump_game.rs b/src/n0055_jump_game.rs index 234624f6..a3634424 100644 --- a/src/n0055_jump_game.rs +++ b/src/n0055_jump_game.rs @@ -2,28 +2,28 @@ * [55] Jump Game * * Given an array of non-negative integers, you are initially positioned at the first index of the array. - * + * * Each element in the array represents your maximum jump length at that position. - * + * * Determine if you are able to reach the last index. - * + * * Example 1: - * - * + * + * * Input: [2,3,1,1,4] * Output: true * Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. - * - * + * + * * Example 2: - * - * + * + * * Input: [3,2,1,0,4] * Output: false * Explanation: You will always arrive at index 3 no matter what. Its maximum * jump length is 0, which makes it impossible to reach the last index. - * - * + * + * */ pub struct Solution {} @@ -49,12 +49,15 @@ mod tests { #[test] fn test_55() { - assert_eq!(Solution::can_jump(vec![2,3,1,1,4]), true); - assert_eq!(Solution::can_jump(vec![3,2,1,0,4]), false); - assert_eq!(Solution::can_jump(vec![2,3,1,1,0,0,0,4]), false); - assert_eq!(Solution::can_jump(vec![8,3,1,1,0,0,0,4]), true); + assert_eq!(Solution::can_jump(vec![2, 3, 1, 1, 4]), true); + assert_eq!(Solution::can_jump(vec![3, 2, 1, 0, 4]), false); + assert_eq!(Solution::can_jump(vec![2, 3, 1, 1, 0, 0, 0, 4]), false); + assert_eq!(Solution::can_jump(vec![8, 3, 1, 1, 0, 0, 0, 4]), true); assert_eq!(Solution::can_jump(vec![0]), true); - assert_eq!(Solution::can_jump(vec![1,1,2,2,0,1,1]), true); - assert_eq!(Solution::can_jump(vec![1,1,1,1,1,1,1,1,1,1,1,1,0]), true); + assert_eq!(Solution::can_jump(vec![1, 1, 2, 2, 0, 1, 1]), true); + assert_eq!( + Solution::can_jump(vec![1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]), + true + ); } } diff --git a/src/n0056_merge_intervals.rs b/src/n0056_merge_intervals.rs index 0e667d60..37b7ade4 100644 --- a/src/n0056_merge_intervals.rs +++ b/src/n0056_merge_intervals.rs @@ -2,56 +2,53 @@ * [56] Merge Intervals * * Given a collection of intervals, merge all overlapping intervals. - * + * * Example 1: - * - * + * + * * Input: [[1,3],[2,6],[8,10],[15,18]] * Output: [[1,6],[8,10],[15,18]] * Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. - * - * + * + * * Example 2: - * - * + * + * * Input: [[1,4],[4,5]] * Output: [[1,5]] * Explanation: Intervals [1,4] and [4,5] are considered overlapping. - * + * */ pub struct Solution {} // submission codes start here // Definition for an interval. - #[derive(Debug, PartialEq, Eq)] - pub struct Interval { - pub start: i32, - pub end: i32, - } +#[derive(Debug, PartialEq, Eq)] +pub struct Interval { + pub start: i32, + pub end: i32, +} - impl Interval { - #[inline] - pub fn new(start: i32, end: i32) -> Self { - Interval { - start, - end - } - } - } +impl Interval { + #[inline] + pub fn new(start: i32, end: i32) -> Self { + Interval { start, end } + } +} impl Solution { pub fn merge(intervals: Vec) -> Vec { let mut intervals = intervals; - intervals.sort_unstable_by_key(|interval| { interval.start }); + intervals.sort_unstable_by_key(|interval| interval.start); let mut result: Vec = Vec::new(); for interval in intervals.into_iter() { match result.last_mut() { Some(mut last_inter) => { if last_inter.end >= interval.start { last_inter.end = i32::max(last_inter.end, interval.end); - continue + continue; } - }, + } None => {} } result.push(interval); @@ -69,8 +66,17 @@ mod tests { #[test] fn test_56() { assert_eq!( - Solution::merge(vec![Interval::new(1,3),Interval::new(2,6),Interval::new(8,10),Interval::new(15,18)]), - vec![Interval::new(1,6),Interval::new(8,10),Interval::new(15,18)] + Solution::merge(vec![ + Interval::new(1, 3), + Interval::new(2, 6), + Interval::new(8, 10), + Interval::new(15, 18) + ]), + vec![ + Interval::new(1, 6), + Interval::new(8, 10), + Interval::new(15, 18) + ] ); } } diff --git a/src/n0057_insert_interval.rs b/src/n0057_insert_interval.rs index e74be393..90294a03 100644 --- a/src/n0057_insert_interval.rs +++ b/src/n0057_insert_interval.rs @@ -2,12 +2,12 @@ * [57] Insert Interval * * Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). - * + * * You may assume that the intervals were initially sorted according to their start times. - * + * * Example 1: - * - * + * + * * Input: intervals = [[1,3],Interval::new(6,9)], newInterval = [2,5] * Output: [[1,5],[6,9]] * @@ -24,22 +24,19 @@ pub struct Solution {} // submission codes start here - // Definition for an interval. - #[derive(Debug, PartialEq, Eq)] - pub struct Interval { - pub start: i32, - pub end: i32, - } +// Definition for an interval. +#[derive(Debug, PartialEq, Eq)] +pub struct Interval { + pub start: i32, + pub end: i32, +} - impl Interval { - #[inline] - pub fn new(start: i32, end: i32) -> Self { - Interval { - start, - end - } - } - } +impl Interval { + #[inline] + pub fn new(start: i32, end: i32) -> Self { + Interval { start, end } + } +} impl Solution { pub fn insert(intervals: Vec, new_interval: Interval) -> Vec { let mut result = Vec::new(); @@ -56,7 +53,8 @@ impl Solution { new_interval.end = i32::max(new_interval.end, interval.end); } else { result.push(Interval::new(new_interval.start, new_interval.end)); - inserting = false; inserted = true; + inserting = false; + inserted = true; } } if !inserting { @@ -79,28 +77,47 @@ mod tests { #[test] fn test_57() { assert_eq!( - Solution::insert(vec![Interval::new(1,3),Interval::new(6,9)], Interval::new(2,5)), - vec![Interval::new(1,5),Interval::new(6,9)] + Solution::insert( + vec![Interval::new(1, 3), Interval::new(6, 9)], + Interval::new(2, 5) + ), + vec![Interval::new(1, 5), Interval::new(6, 9)] ); assert_eq!( - Solution::insert(vec![Interval::new(1,2),Interval::new(3,5),Interval::new(6,7),Interval::new(8,10),Interval::new(12,16)], Interval::new(4,8)), - vec![Interval::new(1,2),Interval::new(3,10),Interval::new(12,16)] + Solution::insert( + vec![ + Interval::new(1, 2), + Interval::new(3, 5), + Interval::new(6, 7), + Interval::new(8, 10), + Interval::new(12, 16) + ], + Interval::new(4, 8) + ), + vec![ + Interval::new(1, 2), + Interval::new(3, 10), + Interval::new(12, 16) + ] ); assert_eq!( - Solution::insert(vec![Interval::new(3,4)], Interval::new(1,2)), - vec![Interval::new(1,2), Interval::new(3,4)] + Solution::insert(vec![Interval::new(3, 4)], Interval::new(1, 2)), + vec![Interval::new(1, 2), Interval::new(3, 4)] ); assert_eq!( - Solution::insert(vec![Interval::new(1,2)], Interval::new(3,4)), - vec![Interval::new(1,2), Interval::new(3,4)] + Solution::insert(vec![Interval::new(1, 2)], Interval::new(3, 4)), + vec![Interval::new(1, 2), Interval::new(3, 4)] ); assert_eq!( - Solution::insert(vec![Interval::new(1,2)], Interval::new(2,3)), - vec![Interval::new(1,3)] + Solution::insert(vec![Interval::new(1, 2)], Interval::new(2, 3)), + vec![Interval::new(1, 3)] ); assert_eq!( - Solution::insert(vec![Interval::new(1,2), Interval::new(3,4)], Interval::new(0,6)), - vec![Interval::new(0,6)] + Solution::insert( + vec![Interval::new(1, 2), Interval::new(3, 4)], + Interval::new(0, 6) + ), + vec![Interval::new(0, 6)] ); } } diff --git a/src/n0058_length_of_last_word.rs b/src/n0058_length_of_last_word.rs index a8a768b7..acd47197 100644 --- a/src/n0058_length_of_last_word.rs +++ b/src/n0058_length_of_last_word.rs @@ -2,17 +2,17 @@ * [58] Length of Last Word * * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. - * + * * If the last word does not exist, return 0. - * + * * Note: A word is defined as a character sequence consists of non-space characters only. - * + * * Example: - * + * * Input: "Hello World" * Output: 5 - * - * + * + * */ pub struct Solution {} diff --git a/src/n0059_spiral_matrix_ii.rs b/src/n0059_spiral_matrix_ii.rs index a443fe47..a9259672 100644 --- a/src/n0059_spiral_matrix_ii.rs +++ b/src/n0059_spiral_matrix_ii.rs @@ -2,10 +2,10 @@ * [59] Spiral Matrix II * * Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. - * + * * Example: - * - * + * + * * Input: 3 * Output: * [ @@ -13,8 +13,8 @@ * [ 8, 9, 4 ], * [ 7, 6, 5 ] * ] - * - * + * + * */ pub struct Solution {} @@ -23,22 +23,44 @@ pub struct Solution {} impl Solution { pub fn generate_matrix(n: i32) -> Vec> { let mut res = vec![vec![0; n as usize]; n as usize]; - if n < 1 { return res } + if n < 1 { + return res; + } let (mut x_min, mut x_max, mut y_min, mut y_max) = (0, n as usize, 0, n as usize); let mut i = 1; loop { - for y in y_min..y_max { res[x_min][y] = i; i+=1; } + for y in y_min..y_max { + res[x_min][y] = i; + i += 1; + } x_min += 1; - if x_min == x_max { break } - for x in x_min..x_max { res[x][y_max-1] = i; i+=1; } + if x_min == x_max { + break; + } + for x in x_min..x_max { + res[x][y_max - 1] = i; + i += 1; + } y_max -= 1; - if y_min == y_max { break } - for y in (y_min..y_max).rev() { res[x_max-1][y] = i; i+=1; } + if y_min == y_max { + break; + } + for y in (y_min..y_max).rev() { + res[x_max - 1][y] = i; + i += 1; + } x_max -= 1; - if x_min == x_max { break } - for x in (x_min..x_max).rev() { res[x][y_min] = i; i+=1; } + if x_min == x_max { + break; + } + for x in (x_min..x_max).rev() { + res[x][y_min] = i; + i += 1; + } y_min += 1; - if y_min == y_max { break } + if y_min == y_max { + break; + } } res } @@ -53,13 +75,10 @@ mod tests { #[test] fn test_59() { assert_eq!(Solution::generate_matrix(1), vec![vec![1]]); - assert_eq!(Solution::generate_matrix(2), vec![vec![1,2],vec![4,3]]); + assert_eq!(Solution::generate_matrix(2), vec![vec![1, 2], vec![4, 3]]); assert_eq!( Solution::generate_matrix(3), - vec![ - vec![1,2,3], - vec![8,9,4], - vec![7,6,5], - ]); + vec![vec![1, 2, 3], vec![8, 9, 4], vec![7, 6, 5],] + ); } } diff --git a/src/n0060_permutation_sequence.rs b/src/n0060_permutation_sequence.rs index 52c9fc65..db0e84d5 100644 --- a/src/n0060_permutation_sequence.rs +++ b/src/n0060_permutation_sequence.rs @@ -2,9 +2,9 @@ * [60] Permutation Sequence * * The set [1,2,3,...,n] contains a total of n! unique permutations. - * + * * By listing and labeling all of the permutations in order, we get the following sequence for n = 3: - * + * *
    * "123" * "132" @@ -13,30 +13,30 @@ * "312" * "321" *
- * + * * Given n and k, return the k^th permutation sequence. - * + * * Note: - * - * + * + * * Given n will be between 1 and 9 inclusive. * Given k will be between 1 and n! inclusive. - * - * + * + * * Example 1: - * - * + * + * * Input: n = 3, k = 3 * Output: "213" - * - * + * + * * Example 2: - * - * + * + * * Input: n = 4, k = 9 * Output: "2314" - * - * + * + * */ pub struct Solution {} @@ -53,9 +53,7 @@ impl Solution { while i > 0 { if k > factorials[i as usize] { let round = k / factorials[i as usize]; - if round >= n { - - } + if round >= n {} } else { i -= 1; } @@ -71,6 +69,5 @@ mod tests { use super::*; #[test] - fn test_60() { - } + fn test_60() {} } diff --git a/src/n0061_rotate_list.rs b/src/n0061_rotate_list.rs index cf6967b1..08812115 100644 --- a/src/n0061_rotate_list.rs +++ b/src/n0061_rotate_list.rs @@ -2,20 +2,20 @@ * [61] Rotate List * * Given a linked list, rotate the list to the right by k places, where k is non-negative. - * + * * Example 1: - * - * + * + * * Input: 1->2->3->4->5->NULL, k = 2 * Output: 4->5->1->2->3->NULL * Explanation: * rotate 1 steps to the right: 5->1->2->3->4->NULL * rotate 2 steps to the right: 4->5->1->2->3->NULL - * - * + * + * * Example 2: - * - * + * + * * Input: 0->1->2->NULL, k = 4 * Output: 2->0->1->NULL * Explanation: @@ -23,10 +23,10 @@ * rotate 2 steps to the right: 1->2->0->NULL * rotate 3 steps to the right: 0->1->2->NULL * rotate 4 steps to the right: 2->0->1->NULL - * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here @@ -43,6 +43,5 @@ mod tests { use super::*; #[test] - fn test_61() { - } + fn test_61() {} } diff --git a/src/n0062_unique_paths.rs b/src/n0062_unique_paths.rs index 23c19bd0..fd3586fe 100644 --- a/src/n0062_unique_paths.rs +++ b/src/n0062_unique_paths.rs @@ -2,19 +2,19 @@ * [62] Unique Paths * * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). - * + * * The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). - * + * * How many possible unique paths are there? - * + * *
* Above is a 7 x 3 grid. How many possible unique paths are there? - * + * * Note: m and n will be at most 100. - * + * * Example 1: - * - * + * + * * Input: m = 3, n = 2 * Output: 3 * Explanation: @@ -22,14 +22,14 @@ * 1. Right -> Right -> Down * 2. Right -> Down -> Right * 3. Down -> Right -> Right - * - * + * + * * Example 2: - * - * + * + * * Input: m = 7, n = 3 * Output: 28 - * + * */ pub struct Solution {} @@ -41,12 +41,15 @@ impl Solution { pub fn unique_paths(m: i32, n: i32) -> i32 { let (m, n) = ((m - 1) as u64, (n - 1) as u64); let sum = m + n; - (Solution::partial_factorial(u64::max(m, n), sum) / Solution::partial_factorial(0, u64::min(m, n))) as i32 + (Solution::partial_factorial(u64::max(m, n), sum) + / Solution::partial_factorial(0, u64::min(m, n))) as i32 } #[inline(always)] pub fn partial_factorial(start: u64, mut end: u64) -> u64 { - if start > end { unreachable!() } + if start > end { + unreachable!() + } let mut res = 1; while end > start { println!("{}", end); diff --git a/src/n0063_unique_paths_ii.rs b/src/n0063_unique_paths_ii.rs index 9702c0d5..84839e23 100644 --- a/src/n0063_unique_paths_ii.rs +++ b/src/n0063_unique_paths_ii.rs @@ -2,20 +2,20 @@ * [63] Unique Paths II * * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). - * + * * The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). - * + * * Now consider if some obstacles are added to the grids. How many unique paths would there be? - * + * * - * + * * An obstacle and empty space is marked as 1 and 0 respectively in the grid. - * + * * Note: m and n will be at most 100. - * + * * Example 1: - * - * + * + * * Input: * [ * [0,0,0], @@ -28,8 +28,8 @@ * There are two ways to reach the bottom-right corner: * 1. Right -> Right -> Down -> Down * 2. Down -> Down -> Right -> Right - * - * + * + * */ pub struct Solution {} @@ -47,17 +47,19 @@ impl Solution { while step <= height + width - 2 { for x in 0..(step + 1) { let y = step - x; - if x >= height || y >= width || obstacle_grid[x][y] == 1 { continue } + if x >= height || y >= width || obstacle_grid[x][y] == 1 { + continue; + } if y >= 1 { - paths[x][y] = paths[x][y] + paths[x][y-1]; + paths[x][y] = paths[x][y] + paths[x][y - 1]; } if x >= 1 { - paths[x][y] = paths[x][y] + paths[x-1][y]; + paths[x][y] = paths[x][y] + paths[x - 1][y]; } } step += 1; } - paths[height-1][width-1] + paths[height - 1][width - 1] } } @@ -71,47 +73,36 @@ mod tests { fn test_63() { assert_eq!(Solution::unique_paths_with_obstacles(vec![vec![0]]), 1); assert_eq!( - Solution::unique_paths_with_obstacles( - vec![ - vec![0, 0], - vec![0, 0], - ] - ), - 2); + Solution::unique_paths_with_obstacles(vec![vec![0, 0], vec![0, 0],]), + 2 + ); assert_eq!( - Solution::unique_paths_with_obstacles( - vec![ - vec![0, 1], - vec![1, 0], - ] - ), - 0); + Solution::unique_paths_with_obstacles(vec![vec![0, 1], vec![1, 0],]), + 0 + ); assert_eq!( - Solution::unique_paths_with_obstacles( - vec![ - vec![0,0,0], - vec![0,1,0], - vec![0,0,0], - ] - ), - 2); + Solution::unique_paths_with_obstacles(vec![ + vec![0, 0, 0], + vec![0, 1, 0], + vec![0, 0, 0], + ]), + 2 + ); assert_eq!( - Solution::unique_paths_with_obstacles( - vec![ - vec![0,0,0,0], - vec![0,0,0,0], - vec![0,0,0,0], - ] - ), - 10); + Solution::unique_paths_with_obstacles(vec![ + vec![0, 0, 0, 0], + vec![0, 0, 0, 0], + vec![0, 0, 0, 0], + ]), + 10 + ); assert_eq!( - Solution::unique_paths_with_obstacles( - vec![ - vec![0,0,0,0], - vec![0,0,0,1], - vec![0,0,1,0], - ] - ), - 0); + Solution::unique_paths_with_obstacles(vec![ + vec![0, 0, 0, 0], + vec![0, 0, 0, 1], + vec![0, 0, 1, 0], + ]), + 0 + ); } } diff --git a/src/n0064_minimum_path_sum.rs b/src/n0064_minimum_path_sum.rs index b4457450..6500e2a3 100644 --- a/src/n0064_minimum_path_sum.rs +++ b/src/n0064_minimum_path_sum.rs @@ -2,12 +2,12 @@ * [64] Minimum Path Sum * * Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. - * + * * Note: You can only move either down or right at any point in time. - * + * * Example: - * - * + * + * * Input: * [ * [1,3,1], @@ -16,8 +16,8 @@ * ] * Output: 7 * Explanation: Because the path 1→3→1→1→1 minimizes the sum. - * - * + * + * */ pub struct Solution {} @@ -29,20 +29,22 @@ impl Solution { let mut grid = grid; let mut step = 1; while step <= height + width - 2 { - for x in 0..(step+1) { + for x in 0..(step + 1) { let y = step - x; - if x >= height || y >= width { continue } + if x >= height || y >= width { + continue; + } if x < 1 { - grid[x][y] += grid[x][y-1]; + grid[x][y] += grid[x][y - 1]; } else if y < 1 { - grid[x][y] += grid[x-1][y]; + grid[x][y] += grid[x - 1][y]; } else { - grid[x][y] += i32::min(grid[x][y-1], grid[x-1][y]); + grid[x][y] += i32::min(grid[x][y - 1], grid[x - 1][y]); } } step += 1; } - grid[height-1][width-1] + grid[height - 1][width - 1] } } @@ -54,25 +56,11 @@ mod tests { #[test] fn test_64() { + assert_eq!(Solution::min_path_sum(vec![vec![2]]), 2); assert_eq!( - Solution::min_path_sum(vec![vec![2]]), - 2 - ); - assert_eq!( - Solution::min_path_sum( - vec![ - vec![1,3,1], - vec![1,5,1], - vec![4,2,1], - ]), + Solution::min_path_sum(vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1],]), 7 ); - assert_eq!( - Solution::min_path_sum( - vec![ - vec![1,3,1], - ]), - 5 - ); + assert_eq!(Solution::min_path_sum(vec![vec![1, 3, 1],]), 5); } } diff --git a/src/n0065_valid_number.rs b/src/n0065_valid_number.rs index fa07c43a..0370784c 100644 --- a/src/n0065_valid_number.rs +++ b/src/n0065_valid_number.rs @@ -2,7 +2,7 @@ * [65] Valid Number * * Validate if a given string can be interpreted as a decimal number. - * + * * Some examples:
* "0" => true
* " 0.1 " => true
@@ -18,21 +18,21 @@ * " --6 " => false
* "-+3" => false
* "95a54e53" => false - * + * * Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number: - * - * + * + * * Numbers 0-9 * Exponent - "e" * Positive/negative sign - "+"/"-" * Decimal point - "." - * - * + * + * * Of course, the context of these characters also matters in the input. - * + * * Update (2015-02-10):
* The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition. - * + * */ pub struct Solution {} @@ -53,6 +53,5 @@ mod tests { use super::*; #[test] - fn test_65() { - } + fn test_65() {} } diff --git a/src/n0066_plus_one.rs b/src/n0066_plus_one.rs index d41f0b6a..ab0bda1a 100644 --- a/src/n0066_plus_one.rs +++ b/src/n0066_plus_one.rs @@ -2,27 +2,27 @@ * [66] Plus One * * Given a non-empty array of digits representing a non-negative integer, plus one to the integer. - * + * * The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. - * + * * You may assume the integer does not contain any leading zero, except the number 0 itself. - * + * * Example 1: - * - * + * + * * Input: [1,2,3] * Output: [1,2,4] * Explanation: The array represents the integer 123. - * - * + * + * * Example 2: - * - * + * + * * Input: [4,3,2,1] * Output: [4,3,2,2] * Explanation: The array represents the integer 4321. - * - * + * + * */ pub struct Solution {} @@ -40,7 +40,9 @@ impl Solution { carry = 0; digits[i] + 1 }; - if carry == 0 { break } + if carry == 0 { + break; + } } if carry > 0 { digits.insert(0, 1); @@ -58,7 +60,10 @@ mod tests { #[test] fn test_66() { assert_eq!(Solution::plus_one(vec![0]), vec![1]); - assert_eq!(Solution::plus_one(vec![9,9,9,9]), vec![1,0,0,0,0]); - assert_eq!(Solution::plus_one(vec![1,0,9,9,9,9]), vec![1,1,0,0,0,0]); + assert_eq!(Solution::plus_one(vec![9, 9, 9, 9]), vec![1, 0, 0, 0, 0]); + assert_eq!( + Solution::plus_one(vec![1, 0, 9, 9, 9, 9]), + vec![1, 1, 0, 0, 0, 0] + ); } } diff --git a/src/n0067_add_binary.rs b/src/n0067_add_binary.rs index 7cc2093c..715824f5 100644 --- a/src/n0067_add_binary.rs +++ b/src/n0067_add_binary.rs @@ -2,21 +2,21 @@ * [67] Add Binary * * Given two binary strings, return their sum (also a binary string). - * + * * The input strings are both non-empty and contains only characters 1 or 0. - * + * * Example 1: - * - * + * + * * Input: a = "11", b = "1" * Output: "100" - * + * * Example 2: - * - * + * + * * Input: a = "1010", b = "1011" * Output: "10101" - * + * */ pub struct Solution {} @@ -25,13 +25,14 @@ pub struct Solution {} use std::char::from_digit; impl Solution { pub fn add_binary(a: String, b: String) -> String { - let mut buf = Vec::with_capacity(usize::max(a.len(), b.len()) + 1); + let mut buf = Vec::with_capacity(usize::max(a.len(), b.len()) + 1); let mut a: Vec = a.chars().collect(); let mut b: Vec = b.chars().collect(); let mut carry = 0; while !(a.is_empty() && b.is_empty()) { let mut sum = a.pop().map_or(0, |ch| ch.to_digit(10).unwrap()) - + b.pop().map_or(0, |ch| ch.to_digit(10).unwrap()) + carry; + + b.pop().map_or(0, |ch| ch.to_digit(10).unwrap()) + + carry; if sum > 1 { sum -= 2; carry = 1; @@ -55,9 +56,21 @@ mod tests { #[test] fn test_67() { - assert_eq!(Solution::add_binary("0".to_owned(), "0".to_owned()), "0".to_owned()); - assert_eq!(Solution::add_binary("1010".to_owned(), "1011".to_owned()), "10101".to_owned()); - assert_eq!(Solution::add_binary("11".to_owned(), "1".to_owned()), "100".to_owned()); - assert_eq!(Solution::add_binary("1111".to_owned(), "1111".to_owned()), "11110".to_owned()); + assert_eq!( + Solution::add_binary("0".to_owned(), "0".to_owned()), + "0".to_owned() + ); + assert_eq!( + Solution::add_binary("1010".to_owned(), "1011".to_owned()), + "10101".to_owned() + ); + assert_eq!( + Solution::add_binary("11".to_owned(), "1".to_owned()), + "100".to_owned() + ); + assert_eq!( + Solution::add_binary("1111".to_owned(), "1111".to_owned()), + "11110".to_owned() + ); } } diff --git a/src/n0068_text_justification.rs b/src/n0068_text_justification.rs index 9b7a08f2..2d8a4fd2 100644 --- a/src/n0068_text_justification.rs +++ b/src/n0068_text_justification.rs @@ -2,24 +2,24 @@ * [68] Text Justification * * Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. - * + * * You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. - * + * * Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. - * + * * For the last line of text, it should be left justified and no extra space is inserted between words. - * + * * Note: - * - * + * + * * A word is defined as a character sequence consisting of non-space characters only. * Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. * The input array words contains at least one word. - * - * + * + * * Example 1: - * - * + * + * * Input: * words = ["This", "is", "an", "example", "of", "text", "justification."] * maxWidth = 16 @@ -29,11 +29,11 @@ * "example of text", * "justification. " * ] - * - * + * + * * Example 2: - * - * + * + * * Input: * words = ["What","must","be","acknowledgment","shall","be"] * maxWidth = 16 @@ -46,11 +46,11 @@ * Explanation: Note that the last line is "shall be " instead of "shall be", * because the last line must be left-justified instead of fully-justified. * Note that the second line is also left-justified becase it contains only one word. - * - * + * + * * Example 3: - * - * + * + * * Input: * words = ["Science","is","what","we","understand","well","enough","to","explain", * "to","a","computer.","Art","is","everything","else","we","do"] @@ -64,8 +64,8 @@ * "everything else we", * "do " * ] - * - * + * + * */ pub struct Solution {} @@ -79,9 +79,11 @@ impl Solution { let mut row_len = 0; let mut buf = Vec::new(); while i < words.len() { - if words[i].len() > max_width { unreachable!() } + if words[i].len() > max_width { + unreachable!() + } let old_len = row_len; - row_len += words[i].len() + if row_len > 0 { 1 } else { 0 }; + row_len += words[i].len() + if row_len > 0 { 1 } else { 0 }; if row_len > max_width { res.push(Solution::compact(buf, max_width, old_len)); buf = Vec::new(); @@ -136,32 +138,50 @@ mod tests { fn test_68() { assert_eq!( Solution::full_justify( - vec_string!["This", "is", "an", "example", "of", "text", "justification."], + vec_string![ + "This", + "is", + "an", + "example", + "of", + "text", + "justification." + ], 16 ), - vec_string![ - "This is an", - "example of text", - "justification. " - ] + vec_string!["This is an", "example of text", "justification. "] ); assert_eq!( Solution::full_justify( - vec_string!["What","must","be","acknowledgment","shall","be"], + vec_string!["What", "must", "be", "acknowledgment", "shall", "be"], 16 ), - vec_string![ - "What must be", - "acknowledgment ", - "shall be " - ] + vec_string!["What must be", "acknowledgment ", "shall be "] ); assert_eq!( Solution::full_justify( - vec_string!["Science","is","what","we","understand","well","enough","to","explain", - "to","a","computer.","Art","is","everything","else","we","do"], + vec_string![ + "Science", + "is", + "what", + "we", + "understand", + "well", + "enough", + "to", + "explain", + "to", + "a", + "computer.", + "Art", + "is", + "everything", + "else", + "we", + "do" + ], 20 ), vec_string![ diff --git a/src/n0069_sqrtx.rs b/src/n0069_sqrtx.rs index 7925061a..5c15c63b 100644 --- a/src/n0069_sqrtx.rs +++ b/src/n0069_sqrtx.rs @@ -2,27 +2,27 @@ * [69] Sqrt(x) * * Implement int sqrt(int x). - * + * * Compute and return the square root of x, where x is guaranteed to be a non-negative integer. - * + * * Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. - * + * * Example 1: - * - * + * + * * Input: 4 * Output: 2 - * - * + * + * * Example 2: - * - * + * + * * Input: 8 * Output: 2 - * Explanation: The square root of 8 is 2.82842..., and since + * Explanation: The square root of 8 is 2.82842..., and since * the decimal part is truncated, 2 is returned. - * - * + * + * */ pub struct Solution {} diff --git a/src/n0070_climbing_stairs.rs b/src/n0070_climbing_stairs.rs index ab90ce83..4a9b44f0 100644 --- a/src/n0070_climbing_stairs.rs +++ b/src/n0070_climbing_stairs.rs @@ -2,32 +2,32 @@ * [70] Climbing Stairs * * You are climbing a stair case. It takes n steps to reach to the top. - * + * * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? - * + * * Note: Given n will be a positive integer. - * + * * Example 1: - * - * + * + * * Input: 2 * Output: 2 * Explanation: There are two ways to climb to the top. * 1. 1 step + 1 step * 2. 2 steps - * - * + * + * * Example 2: - * - * + * + * * Input: 3 * Output: 3 * Explanation: There are three ways to climb to the top. * 1. 1 step + 1 step + 1 step * 2. 1 step + 2 steps * 3. 2 steps + 1 step - * - * + * + * */ pub struct Solution {} @@ -37,8 +37,12 @@ pub struct Solution {} impl Solution { pub fn climb_stairs(n: i32) -> i32 { let n = n as usize; - if n == 1 { return 1 } - if n == 2 { return 2} + if n == 1 { + return 1; + } + if n == 2 { + return 2; + } let (mut prev, mut curr) = (1, 2); for i in 2..n { let next = prev + curr; diff --git a/src/n0071_simplify_path.rs b/src/n0071_simplify_path.rs index e020208a..6b6b909c 100644 --- a/src/n0071_simplify_path.rs +++ b/src/n0071_simplify_path.rs @@ -2,58 +2,58 @@ * [71] Simplify Path * * Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path. - * + * * In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix - * + * * Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path. - * + * * - * + * * Example 1: - * - * + * + * * Input: "/home/" * Output: "/home" * Explanation: Note that there is no trailing slash after the last directory name. - * - * + * + * * Example 2: - * - * + * + * * Input: "/../" * Output: "/" * Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go. - * - * + * + * * Example 3: - * - * + * + * * Input: "/home//foo/" * Output: "/home/foo" * Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one. - * - * + * + * * Example 4: - * - * + * + * * Input: "/a/./b/../../c/" * Output: "/c" - * - * + * + * * Example 5: - * - * + * + * * Input: "/a/../../b/../c//.//" * Output: "/c" - * - * + * + * * Example 6: - * - * + * + * * Input: "/a//b////c/d//././/.." * Output: "/a/b/c" - * - * + * + * */ pub struct Solution {} @@ -64,11 +64,13 @@ impl Solution { let mut stack = Vec::new(); for s in path.split('/') { match s { - "." => {}, - "/" => {}, - "" => {}, - ".." => { stack.pop(); }, - _ => stack.push(s) + "." => {} + "/" => {} + "" => {} + ".." => { + stack.pop(); + } + _ => stack.push(s), } } let mut res = String::new(); @@ -76,7 +78,11 @@ impl Solution { res.push('/'); res.push_str(s); } - if res.len() > 0 { res } else { "/".to_owned() } + if res.len() > 0 { + res + } else { + "/".to_owned() + } } } @@ -91,7 +97,13 @@ mod tests { assert_eq!(Solution::simplify_path("/home/".to_owned()), "/home"); assert_eq!(Solution::simplify_path("/../".to_owned()), "/"); assert_eq!(Solution::simplify_path("/a/./b/../../c/".to_owned()), "/c"); - assert_eq!(Solution::simplify_path("/a/../../b/../c//.//".to_owned()), "/c"); - assert_eq!(Solution::simplify_path("/a//b////c/d//././/..".to_owned()), "/a/b/c"); + assert_eq!( + Solution::simplify_path("/a/../../b/../c//.//".to_owned()), + "/c" + ); + assert_eq!( + Solution::simplify_path("/a//b////c/d//././/..".to_owned()), + "/a/b/c" + ); } } diff --git a/src/n0072_edit_distance.rs b/src/n0072_edit_distance.rs index 8dc9fc09..280518c6 100644 --- a/src/n0072_edit_distance.rs +++ b/src/n0072_edit_distance.rs @@ -2,39 +2,39 @@ * [72] Edit Distance * * Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. - * + * * You have the following 3 operations permitted on a word: - * + * *
    * Insert a character * Delete a character * Replace a character *
- * + * * Example 1: - * - * + * + * * Input: word1 = "horse", word2 = "ros" * Output: 3 - * Explanation: + * Explanation: * horse -> rorse (replace 'h' with 'r') * rorse -> rose (remove 'r') * rose -> ros (remove 'e') - * - * + * + * * Example 2: - * - * + * + * * Input: word1 = "intention", word2 = "execution" * Output: 5 - * Explanation: + * Explanation: * intention -> inention (remove 't') * inention -> enention (replace 'i' with 'e') * enention -> exention (replace 'n' with 'x') * exention -> exection (replace 'n' with 'c') * exection -> execution (insert 'u') - * - * + * + * */ pub struct Solution {} @@ -53,6 +53,5 @@ mod tests { use super::*; #[test] - fn test_72() { - } + fn test_72() {} } diff --git a/src/n0073_set_matrix_zeroes.rs b/src/n0073_set_matrix_zeroes.rs index 17202e5a..cdc73324 100644 --- a/src/n0073_set_matrix_zeroes.rs +++ b/src/n0073_set_matrix_zeroes.rs @@ -1,59 +1,57 @@ /** * [73] Set Matrix Zeroes * - * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. - * - * Example 1: - * - * - * Input: - * [ - * [1,1,1], - * [1,0,1], - * [1,1,1] - * ] - * Output: - * [ - * [1,0,1], - * [0,0,0], - * [1,0,1] - * ] - * - * - * Example 2: - * - * - * Input: - * [ - * [0,1,2,0], - * [3,4,5,2], - * [1,3,1,5] - * ] - * Output: - * [ - * [0,0,0,0], - * [0,4,5,0], - * [0,3,1,0] - * ] - * - * - * Follow up: - * - * - * A straight forward solution using O(mn) space is probably a bad idea. - * A simple improvement uses O(m + n) space, but still not the best solution. - * Could you devise a constant space solution? - * - * + * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. + * + * Example 1: + * + * + * Input: + * [ + * [1,1,1], + * [1,0,1], + * [1,1,1] + * ] + * Output: + * [ + * [1,0,1], + * [0,0,0], + * [1,0,1] + * ] + * + * + * Example 2: + * + * + * Input: + * [ + * [0,1,2,0], + * [3,4,5,2], + * [1,3,1,5] + * ] + * Output: + * [ + * [0,0,0,0], + * [0,4,5,0], + * [0,3,1,0] + * ] + * + * + * Follow up: + * + * + * A straight forward solution using O(mn) space is probably a bad idea. + * A simple improvement uses O(m + n) space, but still not the best solution. + * Could you devise a constant space solution? + * + * */ pub struct Solution {} // submission codes start here impl Solution { - pub fn set_zeroes(matrix: &mut Vec>) { - - } + pub fn set_zeroes(matrix: &mut Vec>) {} } // submission codes end @@ -63,6 +61,5 @@ mod tests { use super::*; #[test] - fn test_73() { - } + fn test_73() {} } diff --git a/src/n0074_search_a_2d_matrix.rs b/src/n0074_search_a_2d_matrix.rs index b58dcb11..e95f02a3 100644 --- a/src/n0074_search_a_2d_matrix.rs +++ b/src/n0074_search_a_2d_matrix.rs @@ -2,15 +2,15 @@ * [74] Search a 2D Matrix * * Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: - * - * + * + * * Integers in each row are sorted from left to right. * The first integer of each row is greater than the last integer of the previous row. - * - * + * + * * Example 1: - * - * + * + * * Input: * matrix = [ * [1, 3, 5, 7], @@ -19,11 +19,11 @@ * ] * target = 3 * Output: true - * - * + * + * * Example 2: - * - * + * + * * Input: * matrix = [ * [1, 3, 5, 7], @@ -32,28 +32,32 @@ * ] * target = 13 * Output: false - * + * */ pub struct Solution {} impl Solution { pub fn search_matrix(matrix: Vec>, target: i32) -> bool { - if matrix.is_empty() { return false } + if matrix.is_empty() { + return false; + } let (height, width) = (matrix.len(), matrix[0].len()); - if height < 1 || width < 1 { return false } + if height < 1 || width < 1 { + return false; + } let mut size = height * width; let mut base = 0_usize; while size > 1 { let half = size / 2; let mid = base + half; - if target == matrix[mid/width][mid%width] { - return true - } else if (target > matrix[mid/width][mid%width]) { + if target == matrix[mid / width][mid % width] { + return true; + } else if (target > matrix[mid / width][mid % width]) { base = mid; } size -= half; } - target == matrix[base/width][base%width] + target == matrix[base / width][base % width] } } @@ -67,21 +71,15 @@ mod tests { fn test_74() { assert_eq!( Solution::search_matrix( - vec![ - vec![1, 3, 5, 7], - vec![10, 11, 16, 20], - vec![23, 30, 34, 50] - ], 3 + vec![vec![1, 3, 5, 7], vec![10, 11, 16, 20], vec![23, 30, 34, 50]], + 3 ), true ); assert_eq!( Solution::search_matrix( - vec![ - vec![1, 3, 5, 7], - vec![10, 11, 16, 20], - vec![23, 30, 34, 50] - ], 13 + vec![vec![1, 3, 5, 7], vec![10, 11, 16, 20], vec![23, 30, 34, 50]], + 13 ), false ); diff --git a/src/n0075_sort_colors.rs b/src/n0075_sort_colors.rs index fda4f61c..8276ea52 100644 --- a/src/n0075_sort_colors.rs +++ b/src/n0075_sort_colors.rs @@ -2,25 +2,25 @@ * [75] Sort Colors * * Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. - * + * * Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. - * + * * Note: You are not suppose to use the library's sort function for this problem. - * + * * Example: - * - * + * + * * Input: [2,0,2,1,1,0] * Output: [0,0,1,1,2,2] - * + * * Follow up: - * - * + * + * * A rather straight forward solution is a two-pass algorithm using counting sort.
* First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. * Could you come up with a one-pass algorithm using only constant space? - * - * + * + * */ pub struct Solution {} @@ -29,17 +29,22 @@ pub struct Solution {} // three-way partition impl Solution { pub fn sort_colors(nums: &mut Vec) { - if nums.is_empty() { return } - let (mut lower_idx, mut upper_idx) = (0_usize, nums.len()-1); + if nums.is_empty() { + return; + } + let (mut lower_idx, mut upper_idx) = (0_usize, nums.len() - 1); let mut i = 0_usize; while i <= upper_idx { if nums[i] < 1 { // lower_idx <= i, we've scanned it so we know nums[lower_idx] <= 1, i++ nums.swap(lower_idx, i); - i += 1; lower_idx += 1; + i += 1; + lower_idx += 1; } else if nums[i] > 1 { nums.swap(upper_idx, i); - if upper_idx < 1 { break } + if upper_idx < 1 { + break; + } upper_idx -= 1; } else { i += 1; @@ -56,16 +61,21 @@ mod tests { #[test] fn test_75() { - let mut vec = vec![1,2,0,1,2,2,2,0,0,0,2,1,1,2,0,1,2,2,1,1,0]; + let mut vec = vec![ + 1, 2, 0, 1, 2, 2, 2, 0, 0, 0, 2, 1, 1, 2, 0, 1, 2, 2, 1, 1, 0, + ]; Solution::sort_colors(&mut vec); - assert_eq!(vec, vec![0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2]); + assert_eq!( + vec, + vec![0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2] + ); let mut vec = vec![]; Solution::sort_colors(&mut vec); assert_eq!(vec, vec![]); - let mut vec = vec![2,2,2]; + let mut vec = vec![2, 2, 2]; Solution::sort_colors(&mut vec); - assert_eq!(vec, vec![2,2,2]); + assert_eq!(vec, vec![2, 2, 2]); } } diff --git a/src/n0076_minimum_window_substring.rs b/src/n0076_minimum_window_substring.rs index 5ec5e7c5..1eaa1ab9 100644 --- a/src/n0076_minimum_window_substring.rs +++ b/src/n0076_minimum_window_substring.rs @@ -2,21 +2,21 @@ * [76] Minimum Window Substring * * Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). - * + * * Example: - * - * + * + * * Input: S = "ADOBECODEBANC", T = "ABC" * Output: "BANC" - * - * + * + * * Note: - * - * + * + * * If there is no such window in S that covers all characters in T, return the empty string "". * If there is such window, you are guaranteed that there will always be only one unique minimum window in S. - * - * + * + * */ pub struct Solution {} @@ -25,13 +25,11 @@ use std::collections::HashMap; impl Solution { pub fn min_window(s: String, t: String) -> String { if t.is_empty() || t.len() > s.len() { - return "".to_owned() + return "".to_owned(); } let (mut start, mut end) = (0_usize, 0_usize); - let mut result = (0_usize,0_usize); - loop { - - } + let mut result = (0_usize, 0_usize); + loop {} s[result.0..result.1].to_owned() } @@ -51,6 +49,5 @@ mod tests { use super::*; #[test] - fn test_76() { - } + fn test_76() {} } diff --git a/src/n0077_combinations.rs b/src/n0077_combinations.rs index 0a9d2d1a..c5e56f80 100644 --- a/src/n0077_combinations.rs +++ b/src/n0077_combinations.rs @@ -2,10 +2,10 @@ * [77] Combinations * * Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. - * + * * Example: - * - * + * + * * Input: n = 4, k = 2 * Output: * [ @@ -16,8 +16,8 @@ * [1,3], * [1,4], * ] - * - * + * + * */ pub struct Solution {} @@ -33,16 +33,16 @@ impl Solution { fn backtrack(start: i32, end: i32, k: i32, curr: Vec, result: &mut Vec>) { if k < 1 { result.push(curr); - return + return; } if end - start + 1 < k { // elements is not enough, return quickly - return + return; } - for i in start..end+1 { + for i in start..end + 1 { let mut vec = curr.clone(); vec.push(i); - Solution::backtrack(i+1, end, k-1, vec, result); + Solution::backtrack(i + 1, end, k - 1, vec, result); } } } @@ -57,20 +57,18 @@ mod tests { fn test_77() { assert_eq!( Solution::combine(4, 2), - vec![vec![1, 2], vec![1, 3], vec![1, 4], vec![2, 3], vec![2, 4], vec![3, 4]] - ); - assert_eq!( - Solution::combine(1, 1), - vec![vec![1]] + vec![ + vec![1, 2], + vec![1, 3], + vec![1, 4], + vec![2, 3], + vec![2, 4], + vec![3, 4] + ] ); + assert_eq!(Solution::combine(1, 1), vec![vec![1]]); let empty: Vec> = vec![]; - assert_eq!( - Solution::combine(0, 1), - empty - ); - assert_eq!( - Solution::combine(2, 1), - vec![vec![1], vec![2]] - ); + assert_eq!(Solution::combine(0, 1), empty); + assert_eq!(Solution::combine(2, 1), vec![vec![1], vec![2]]); } } diff --git a/src/n0078_subsets.rs b/src/n0078_subsets.rs index d2077a9e..95757486 100644 --- a/src/n0078_subsets.rs +++ b/src/n0078_subsets.rs @@ -2,12 +2,12 @@ * [78] Subsets * * Given a set of distinct integers, nums, return all possible subsets (the power set). - * + * * Note: The solution set must not contain duplicate subsets. - * + * * Example: - * - * + * + * * Input: nums = [1,2,3] * Output: * [ @@ -20,7 +20,7 @@ * [1,2], * [] * ] - * + * */ pub struct Solution {} @@ -36,13 +36,13 @@ impl Solution { fn backtrack(start: usize, mut curr: Vec, nums: &Vec, result: &mut Vec>) { if start >= nums.len() { result.push(curr); - return + return; } // current element dropped - Solution::backtrack(start+1, curr.clone(), nums, result); + Solution::backtrack(start + 1, curr.clone(), nums, result); // current element picked curr.push(nums[start]); - Solution::backtrack(start+1, curr, nums, result); + Solution::backtrack(start + 1, curr, nums, result); } } @@ -54,18 +54,11 @@ mod tests { #[test] fn test_78() { + assert_eq!(Solution::subsets(vec![]), vec![vec![]]); + assert_eq!(Solution::subsets(vec![1]), vec![vec![], vec![1]]); assert_eq!( - Solution::subsets(vec![]), - vec![vec![]] + Solution::subsets(vec![1, 2]), + vec![vec![], vec![2], vec![1], vec![1, 2]] ); - assert_eq!( - Solution::subsets(vec![1]), - vec![vec![],vec![1]] - ); - assert_eq!( - Solution::subsets(vec![1,2]), - vec![vec![],vec![2],vec![1],vec![1,2]] - ); - } } diff --git a/src/n0079_word_search.rs b/src/n0079_word_search.rs index 5c11be33..fa02e3ad 100644 --- a/src/n0079_word_search.rs +++ b/src/n0079_word_search.rs @@ -2,24 +2,24 @@ * [79] Word Search * * Given a 2D board and a word, find if the word exists in the grid. - * + * * The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. - * + * * Example: - * - * + * + * * board = * [ * ['A','B','C','E'], * ['S','F','C','S'], * ['A','D','E','E'] * ] - * + * * Given word = "ABCCED", return true. * Given word = "SEE", return true. * Given word = "ABCB", return false. - * - * + * + * */ pub struct Solution {} @@ -28,35 +28,59 @@ pub struct Solution {} // TODO: use HashSet to record visited pos impl Solution { pub fn exist(board: Vec>, word: String) -> bool { - if board.is_empty() || word.len() < 1 { return false } + if board.is_empty() || word.len() < 1 { + return false; + } let (height, width) = (board.len(), board[0].len()); - if height < 1 || width < 1 { return false } + if height < 1 || width < 1 { + return false; + } let seq: Vec = word.chars().collect(); - for i in 0..height*width { - if Solution::dfs(i/width, i%width, &seq[..], &board, vec![], height, width) { - return true + for i in 0..height * width { + if Solution::dfs( + i / width, + i % width, + &seq[..], + &board, + vec![], + height, + width, + ) { + return true; } } false } - fn dfs(x: usize, y: usize, seq: &[char], board: &Vec>, mut visited: Vec<(usize, usize)>, height: usize, width: usize) -> bool { + fn dfs( + x: usize, + y: usize, + seq: &[char], + board: &Vec>, + mut visited: Vec<(usize, usize)>, + height: usize, + width: usize, + ) -> bool { if seq[0] != board[x][y] { - return false + return false; } if seq.len() < 2 { - return true + return true; } - visited.push((x,y)); - return (x > 0 && !visited.contains(&(x-1,y)) - && Solution::dfs(x-1, y, &seq[1..], board, visited.clone(), height, width)) - || (x+1 < height && !visited.contains(&(x+1,y)) - && Solution::dfs(x+1, y, &seq[1..], board, visited.clone(), height, width)) - || (y > 0 && !visited.contains(&(x,y-1)) - && Solution::dfs(x, y-1, &seq[1..], board, visited.clone(), height, width)) - || (y+1 < width && !visited.contains(&(x,y+1)) - && Solution::dfs(x, y+1, &seq[1..], board, visited.clone(), height, width)); + visited.push((x, y)); + return (x > 0 + && !visited.contains(&(x - 1, y)) + && Solution::dfs(x - 1, y, &seq[1..], board, visited.clone(), height, width)) + || (x + 1 < height + && !visited.contains(&(x + 1, y)) + && Solution::dfs(x + 1, y, &seq[1..], board, visited.clone(), height, width)) + || (y > 0 + && !visited.contains(&(x, y - 1)) + && Solution::dfs(x, y - 1, &seq[1..], board, visited.clone(), height, width)) + || (y + 1 < width + && !visited.contains(&(x, y + 1)) + && Solution::dfs(x, y + 1, &seq[1..], board, visited.clone(), height, width)); } } @@ -68,38 +92,38 @@ mod tests { #[test] fn test_79() { - assert_eq!( - Solution::exist(vec![vec!['a']], "a".to_owned()), - true - ); + assert_eq!(Solution::exist(vec![vec!['a']], "a".to_owned()), true); assert_eq!( Solution::exist( vec![ - vec!['A','B','C','E'], - vec!['S','F','C','S'], - vec!['A','D','E','E'], + vec!['A', 'B', 'C', 'E'], + vec!['S', 'F', 'C', 'S'], + vec!['A', 'D', 'E', 'E'], ], - "ABCCED".to_owned()), + "ABCCED".to_owned() + ), true ); assert_eq!( Solution::exist( vec![ - vec!['A','B','C','E'], - vec!['S','F','C','S'], - vec!['A','D','E','E'], + vec!['A', 'B', 'C', 'E'], + vec!['S', 'F', 'C', 'S'], + vec!['A', 'D', 'E', 'E'], ], - "SEE".to_owned()), + "SEE".to_owned() + ), true ); assert_eq!( Solution::exist( vec![ - vec!['A','B','C','E'], - vec!['S','F','C','S'], - vec!['A','D','E','E'], + vec!['A', 'B', 'C', 'E'], + vec!['S', 'F', 'C', 'S'], + vec!['A', 'D', 'E', 'E'], ], - "ABCB".to_owned()), + "ABCB".to_owned() + ), false ); } diff --git a/src/n0080_remove_duplicates_from_sorted_array_ii.rs b/src/n0080_remove_duplicates_from_sorted_array_ii.rs index 81258613..1ba2e2e9 100644 --- a/src/n0080_remove_duplicates_from_sorted_array_ii.rs +++ b/src/n0080_remove_duplicates_from_sorted_array_ii.rs @@ -2,47 +2,47 @@ * [80] Remove Duplicates from Sorted Array II * * Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length. - * + * * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. - * + * * Example 1: - * - * + * + * * Given nums = [1,1,1,2,2,3], - * + * * Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. - * + * * It doesn't matter what you leave beyond the returned length. - * + * * Example 2: - * - * + * + * * Given nums = [0,0,1,1,1,1,2,3,3], - * + * * Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively. - * + * * It doesn't matter what values are set beyond the returned length. - * - * + * + * * Clarification: - * + * * Confused why the returned value is an integer but your answer is an array? - * + * * Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. - * + * * Internally you can think of this: - * - * + * + * * // nums is passed in by reference. (i.e., without making a copy) * int len = removeDuplicates(nums); - * + * * // any modification to nums in your function would be known by the caller. * // using the length returned by your function, it prints the first len elements. * for (int i = 0; i < len; i++) { * print(nums[i]); * } - * - * + * + * */ pub struct Solution {} @@ -61,6 +61,5 @@ mod tests { use super::*; #[test] - fn test_80() { - } + fn test_80() {} } diff --git a/src/n0081_search_in_rotated_sorted_array_ii.rs b/src/n0081_search_in_rotated_sorted_array_ii.rs index b1824900..d7f841d7 100644 --- a/src/n0081_search_in_rotated_sorted_array_ii.rs +++ b/src/n0081_search_in_rotated_sorted_array_ii.rs @@ -2,31 +2,31 @@ * [81] Search in Rotated Sorted Array II * * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. - * + * * (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). - * + * * You are given a target value to search. If found in the array return true, otherwise return false. - * + * * Example 1: - * - * + * + * * Input: nums = [2,5,6,0,0,1,2], target = 0 * Output: true - * - * + * + * * Example 2: - * - * + * + * * Input: nums = [2,5,6,0,0,1,2], target = 3 * Output: false - * + * * Follow up: - * - * + * + * * This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates. * Would this affect the run-time complexity? How and why? - * - * + * + * */ pub struct Solution {} @@ -45,6 +45,5 @@ mod tests { use super::*; #[test] - fn test_81() { - } + fn test_81() {} } diff --git a/src/n0082_remove_duplicates_from_sorted_list_ii.rs b/src/n0082_remove_duplicates_from_sorted_list_ii.rs index 7f26a25b..ff8c8b8b 100644 --- a/src/n0082_remove_duplicates_from_sorted_list_ii.rs +++ b/src/n0082_remove_duplicates_from_sorted_list_ii.rs @@ -2,24 +2,24 @@ * [82] Remove Duplicates from Sorted List II * * Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. - * + * * Example 1: - * - * + * + * * Input: 1->2->3->3->4->4->5 * Output: 1->2->5 - * - * + * + * * Example 2: - * - * + * + * * Input: 1->1->1->2->3 * Output: 2->3 - * - * + * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here @@ -29,7 +29,7 @@ use super::util::linked_list::{ListNode, to_list}; // pub val: i32, // pub next: Option> // } -// +// // impl ListNode { // #[inline] // fn new(val: i32) -> Self { @@ -52,6 +52,5 @@ mod tests { use super::*; #[test] - fn test_82() { - } + fn test_82() {} } diff --git a/src/n0083_remove_duplicates_from_sorted_list.rs b/src/n0083_remove_duplicates_from_sorted_list.rs index 6030c791..b8fa539f 100644 --- a/src/n0083_remove_duplicates_from_sorted_list.rs +++ b/src/n0083_remove_duplicates_from_sorted_list.rs @@ -2,24 +2,24 @@ * [83] Remove Duplicates from Sorted List * * Given a sorted linked list, delete all duplicates such that each element appear only once. - * + * * Example 1: - * - * + * + * * Input: 1->1->2 * Output: 1->2 - * - * + * + * * Example 2: - * - * + * + * * Input: 1->1->2->3->3 * Output: 1->2->3 - * - * + * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here @@ -29,7 +29,7 @@ use super::util::linked_list::{ListNode, to_list}; // pub val: i32, // pub next: Option> // } -// +// // impl ListNode { // #[inline] // fn new(val: i32) -> Self { @@ -52,6 +52,5 @@ mod tests { use super::*; #[test] - fn test_83() { - } + fn test_83() {} } diff --git a/src/n0084_largest_rectangle_in_histogram.rs b/src/n0084_largest_rectangle_in_histogram.rs index 0440e557..19b845a0 100644 --- a/src/n0084_largest_rectangle_in_histogram.rs +++ b/src/n0084_largest_rectangle_in_histogram.rs @@ -2,26 +2,26 @@ * [84] Largest Rectangle in Histogram * * Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. - * + * * - * + * *
* Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. - * + * * - * + * *
* The largest rectangle is shown in the shaded area, which has area = 10 unit. - * + * * - * + * * Example: - * - * + * + * * Input: [2,1,5,6,2,3] * Output: 10 - * - * + * + * */ pub struct Solution {} @@ -37,16 +37,26 @@ impl Solution { for (i, h) in heights.into_iter().enumerate() { let mut last_pop = None; while hs.last().is_some() && *hs.last().unwrap() >= h { - max_area = i32::max(max_area, hs.last().unwrap() * ((i - positions.last().unwrap()) as i32)); + max_area = i32::max( + max_area, + hs.last().unwrap() * ((i - positions.last().unwrap()) as i32), + ); hs.pop(); last_pop = positions.pop(); } - if last_pop.is_some() { positions.push(last_pop.unwrap()); } else { positions.push(i); } + if last_pop.is_some() { + positions.push(last_pop.unwrap()); + } else { + positions.push(i); + } hs.push(h); } // drain stack while !hs.is_empty() { - max_area = i32::max(max_area, hs.last().unwrap() * ((len - positions.last().unwrap()) as i32)); + max_area = i32::max( + max_area, + hs.last().unwrap() * ((len - positions.last().unwrap()) as i32), + ); positions.pop(); hs.pop(); } @@ -62,11 +72,17 @@ mod tests { #[test] fn test_84() { - assert_eq!(Solution::largest_rectangle_area(vec![2,1,5,6,2,3]), 10); - assert_eq!(Solution::largest_rectangle_area(vec![1,1,1,1,1,1,1,1]), 8); - assert_eq!(Solution::largest_rectangle_area(vec![2,2]), 4); - assert_eq!(Solution::largest_rectangle_area(vec![1,2,8,8,2,2,1]), 16); - assert_eq!(Solution::largest_rectangle_area(vec![2,1,2]), 3); - assert_eq!(Solution::largest_rectangle_area(vec![1,3,2,1,2]), 5); + assert_eq!(Solution::largest_rectangle_area(vec![2, 1, 5, 6, 2, 3]), 10); + assert_eq!( + Solution::largest_rectangle_area(vec![1, 1, 1, 1, 1, 1, 1, 1]), + 8 + ); + assert_eq!(Solution::largest_rectangle_area(vec![2, 2]), 4); + assert_eq!( + Solution::largest_rectangle_area(vec![1, 2, 8, 8, 2, 2, 1]), + 16 + ); + assert_eq!(Solution::largest_rectangle_area(vec![2, 1, 2]), 3); + assert_eq!(Solution::largest_rectangle_area(vec![1, 3, 2, 1, 2]), 5); } } diff --git a/src/n0085_maximal_rectangle.rs b/src/n0085_maximal_rectangle.rs index 921e69d7..878236ef 100644 --- a/src/n0085_maximal_rectangle.rs +++ b/src/n0085_maximal_rectangle.rs @@ -2,10 +2,10 @@ * [85] Maximal Rectangle * * Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. - * + * * Example: - * - * + * + * * Input: * [ * ["1","0","1","0","0"], @@ -14,8 +14,8 @@ * ["1","0","0","1","0"] * ] * Output: 6 - * - * + * + * */ pub struct Solution {} @@ -24,7 +24,7 @@ pub struct Solution {} impl Solution { pub fn maximal_rectangle(matrix: Vec>) -> i32 { let mut max_area = 0; - + max_area } } @@ -36,6 +36,5 @@ mod tests { use super::*; #[test] - fn test_85() { - } + fn test_85() {} } diff --git a/src/n0086_partition_list.rs b/src/n0086_partition_list.rs index a4c847b2..ad03b081 100644 --- a/src/n0086_partition_list.rs +++ b/src/n0086_partition_list.rs @@ -2,19 +2,19 @@ * [86] Partition List * * Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. - * + * * You should preserve the original relative order of the nodes in each of the two partitions. - * + * * Example: - * - * + * + * * Input: head = 1->4->3->2->5->2, x = 3 * Output: 1->2->2->4->3->5 - * - * + * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; impl Solution { pub fn partition(head: Option>, x: i32) -> Option> { @@ -48,16 +48,13 @@ mod tests { #[test] fn test_86() { assert_eq!( - Solution::partition(linked![1,4,3,2,5,2], 3), - linked![1,2,2,4,3,5] - ); - assert_eq!( - Solution::partition(linked![1,4,3,2,5,2], 8), - linked![1,4,3,2,5,2] + Solution::partition(linked![1, 4, 3, 2, 5, 2], 3), + linked![1, 2, 2, 4, 3, 5] ); assert_eq!( - Solution::partition(linked![], 0), - linked![] + Solution::partition(linked![1, 4, 3, 2, 5, 2], 8), + linked![1, 4, 3, 2, 5, 2] ); + assert_eq!(Solution::partition(linked![], 0), linked![]); } } diff --git a/src/n0087_scramble_string.rs b/src/n0087_scramble_string.rs index c2601ade..5b70a69a 100644 --- a/src/n0087_scramble_string.rs +++ b/src/n0087_scramble_string.rs @@ -2,10 +2,10 @@ * [87] Scramble String * * Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. - * + * * Below is one possible representation of s1 = "great": - * - * + * + * * great * / \ * gr eat @@ -13,13 +13,13 @@ * g r e at * / \ * a t - * - * + * + * * To scramble the string, we may choose any non-leaf node and swap its two children. - * + * * For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat". - * - * + * + * * rgeat * / \ * rg eat @@ -27,13 +27,13 @@ * r g e at * / \ * a t - * - * + * + * * We say that "rgeat" is a scrambled string of "great". - * + * * Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae". - * - * + * + * * rgtae * / \ * rg tae @@ -41,25 +41,25 @@ * r g ta e * / \ * t a - * - * + * + * * We say that "rgtae" is a scrambled string of "great". - * + * * Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1. - * + * * Example 1: - * - * + * + * * Input: s1 = "great", s2 = "rgeat" * Output: true - * - * + * + * * Example 2: - * - * + * + * * Input: s1 = "abcde", s2 = "caebd" * Output: false - * + * */ pub struct Solution {} @@ -78,6 +78,5 @@ mod tests { use super::*; #[test] - fn test_87() { - } + fn test_87() {} } diff --git a/src/n0088_merge_sorted_array.rs b/src/n0088_merge_sorted_array.rs index e9266f6a..955d5ad9 100644 --- a/src/n0088_merge_sorted_array.rs +++ b/src/n0088_merge_sorted_array.rs @@ -2,24 +2,24 @@ * [88] Merge Sorted Array * * Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. - * + * * Note: - * - * + * + * * The number of elements initialized in nums1 and nums2 are m and n respectively. * You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. - * - * + * + * * Example: - * - * + * + * * Input: * nums1 = [1,2,3,0,0,0], m = 3 * nums2 = [2,5,6], n = 3 - * + * * Output: [1,2,2,3,5,6] - * - * + * + * */ pub struct Solution {} @@ -51,28 +51,19 @@ mod tests { #[test] fn test_88() { - let mut vec1 = vec![1,2,3,0,0,0]; - let mut vec2 = vec![2,5,6]; + let mut vec1 = vec![1, 2, 3, 0, 0, 0]; + let mut vec2 = vec![2, 5, 6]; Solution::merge(&mut vec1, 3, &mut vec2, 3); - assert_eq!( - vec1, - vec![1,2,2,3,5,6] - ); + assert_eq!(vec1, vec![1, 2, 2, 3, 5, 6]); - let mut vec1 = vec![1,2,3]; + let mut vec1 = vec![1, 2, 3]; let mut vec2 = vec![]; Solution::merge(&mut vec1, 3, &mut vec2, 0); - assert_eq!( - vec1, - vec![1,2,3] - ); + assert_eq!(vec1, vec![1, 2, 3]); - let mut vec1 = vec![0,0,0]; - let mut vec2 = vec![1,2,3]; + let mut vec1 = vec![0, 0, 0]; + let mut vec2 = vec![1, 2, 3]; Solution::merge(&mut vec1, 0, &mut vec2, 3); - assert_eq!( - vec1, - vec![1,2,3] - ); + assert_eq!(vec1, vec![1, 2, 3]); } } diff --git a/src/n0089_gray_code.rs b/src/n0089_gray_code.rs index eb4515f4..0bc4ffc0 100644 --- a/src/n0089_gray_code.rs +++ b/src/n0089_gray_code.rs @@ -2,12 +2,12 @@ * [89] Gray Code * * The gray code is a binary numeral system where two successive values differ in only one bit. - * + * * Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. - * + * * Example 1: - * - * + * + * * Input: 2 * Output: [0,1,3,2] * Explanation: @@ -15,26 +15,26 @@ * 01 - 1 * 11 - 3 * 10 - 2 - * + * * For a given n, a gray code sequence may not be uniquely defined. * For example, [0,2,3,1] is also a valid gray code sequence. - * + * * 00 - 0 * 10 - 2 * 11 - 3 * 01 - 1 - * - * + * + * * Example 2: - * - * + * + * * Input: 0 * Output: [0] * Explanation: We define the gray code sequence to begin with 0. * A gray code sequence of n has size = 2^n, which for n = 0 the size is 2^0 = 1. * Therefore, for n = 0 the gray code sequence is [0]. - * - * + * + * */ pub struct Solution {} @@ -71,9 +71,9 @@ mod tests { #[test] fn test_89() { - assert_eq!(Solution::gray_code(2), vec![0,1,3,2]); - assert_eq!(Solution::gray_code(1), vec![0,1]); + assert_eq!(Solution::gray_code(2), vec![0, 1, 3, 2]); + assert_eq!(Solution::gray_code(1), vec![0, 1]); assert_eq!(Solution::gray_code(0), vec![0]); - assert_eq!(Solution::gray_code(3), vec![0,1,3,2,6,7,5,4]); + assert_eq!(Solution::gray_code(3), vec![0, 1, 3, 2, 6, 7, 5, 4]); } } diff --git a/src/n0090_subsets_ii.rs b/src/n0090_subsets_ii.rs index 4b74ecc9..80d17be6 100644 --- a/src/n0090_subsets_ii.rs +++ b/src/n0090_subsets_ii.rs @@ -2,12 +2,12 @@ * [90] Subsets II * * Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). - * + * * Note: The solution set must not contain duplicate subsets. - * + * * Example: - * - * + * + * * Input: [1,2,2] * Output: * [ @@ -18,42 +18,51 @@ * [1,2], * [] * ] - * - * + * + * */ pub struct Solution {} // submission codes start here /* - count the repeats of each number, - then in backtracking, each number can be picked up for 0..repeat times +count the repeats of each number, +then in backtracking, each number can be picked up for 0..repeat times - using BTreeMap to preserve order (easy for test) - */ +using BTreeMap to preserve order (easy for test) +*/ use std::collections::BTreeMap; impl Solution { pub fn subsets_with_dup(nums: Vec) -> Vec> { let mut res = Vec::new(); - let nums = nums.into_iter() + let nums = nums + .into_iter() .fold(BTreeMap::new(), |mut map, v| { - *map.entry(v).or_insert(0) += 1; map - }).into_iter().collect::>(); + *map.entry(v).or_insert(0) += 1; + map + }) + .into_iter() + .collect::>(); Solution::backtrack(0, vec![], &nums, &mut res); res } - fn backtrack(start: usize, mut curr: Vec, nums: &Vec<(i32, i32)>, result: &mut Vec>) { + fn backtrack( + start: usize, + mut curr: Vec, + nums: &Vec<(i32, i32)>, + result: &mut Vec>, + ) { if start >= nums.len() { result.push(curr); - return + return; } - for repeat in 0..nums[start].1+1 { + for repeat in 0..nums[start].1 + 1 { let mut inner = curr.clone(); for _ in 0..repeat { inner.push(nums[start].0); } - Solution::backtrack(start+1, inner, nums, result); + Solution::backtrack(start + 1, inner, nums, result); } } } @@ -67,28 +76,17 @@ mod tests { #[test] fn test_90() { assert_eq!( - Solution::subsets_with_dup(vec![1,2,2]), + Solution::subsets_with_dup(vec![1, 2, 2]), vec![ vec![], vec![2], - vec![2,2], - vec![1], - vec![1,2], - vec![1,2,2], - ] - ); - assert_eq!( - Solution::subsets_with_dup(vec![1]), - vec![ - vec![], + vec![2, 2], vec![1], + vec![1, 2], + vec![1, 2, 2], ] ); - assert_eq!( - Solution::subsets_with_dup(vec![]), - vec![ - vec![], - ] - ); + assert_eq!(Solution::subsets_with_dup(vec![1]), vec![vec![], vec![1],]); + assert_eq!(Solution::subsets_with_dup(vec![]), vec![vec![],]); } } diff --git a/src/n0091_decode_ways.rs b/src/n0091_decode_ways.rs index b10aaf8e..a181c137 100644 --- a/src/n0091_decode_ways.rs +++ b/src/n0091_decode_ways.rs @@ -2,31 +2,31 @@ * [91] Decode Ways * * A message containing letters from A-Z is being encoded to numbers using the following mapping: - * - * + * + * * 'A' -> 1 * 'B' -> 2 * ... * 'Z' -> 26 - * - * + * + * * Given a non-empty string containing only digits, determine the total number of ways to decode it. - * + * * Example 1: - * - * + * + * * Input: "12" * Output: 2 * Explanation: It could be decoded as "AB" (1 2) or "L" (12). - * - * + * + * * Example 2: - * - * + * + * * Input: "226" * Output: 3 * Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). - * + * */ pub struct Solution {} @@ -45,6 +45,5 @@ mod tests { use super::*; #[test] - fn test_91() { - } + fn test_91() {} } diff --git a/src/n0092_reverse_linked_list_ii.rs b/src/n0092_reverse_linked_list_ii.rs index 09f10862..705a7875 100644 --- a/src/n0092_reverse_linked_list_ii.rs +++ b/src/n0092_reverse_linked_list_ii.rs @@ -2,19 +2,19 @@ * [92] Reverse Linked List II * * Reverse a linked list from position m to n. Do it in one-pass. - * + * * Note: 1 ≤ m ≤ n ≤ length of list. - * + * * Example: - * - * + * + * * Input: 1->2->3->4->5->NULL, m = 2, n = 4 * Output: 1->4->3->2->5->NULL - * - * + * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here @@ -24,7 +24,7 @@ use super::util::linked_list::{ListNode, to_list}; // pub val: i32, // pub next: Option> // } -// +// // impl ListNode { // #[inline] // fn new(val: i32) -> Self { @@ -47,6 +47,5 @@ mod tests { use super::*; #[test] - fn test_92() { - } + fn test_92() {} } diff --git a/src/n0093_restore_ip_addresses.rs b/src/n0093_restore_ip_addresses.rs index 38f602bb..08d0a8ec 100644 --- a/src/n0093_restore_ip_addresses.rs +++ b/src/n0093_restore_ip_addresses.rs @@ -2,14 +2,14 @@ * [93] Restore IP Addresses * * Given a string containing only digits, restore it by returning all possible valid IP address combinations. - * + * * Example: - * - * + * + * * Input: "25525511135" * Output: ["255.255.11.135", "255.255.111.35"] - * - * + * + * */ pub struct Solution {} @@ -28,6 +28,5 @@ mod tests { use super::*; #[test] - fn test_93() { - } + fn test_93() {} } diff --git a/src/n0094_binary_tree_inorder_traversal.rs b/src/n0094_binary_tree_inorder_traversal.rs index 42e55545..c40cd1c8 100644 --- a/src/n0094_binary_tree_inorder_traversal.rs +++ b/src/n0094_binary_tree_inorder_traversal.rs @@ -2,33 +2,33 @@ * [94] Binary Tree Inorder Traversal * * Given a binary tree, return the inorder traversal of its nodes' values. - * + * * Example: - * - * + * + * * Input: [1,null,2,3] * 1 * \ * 2 * / * 3 - * + * * Output: [1,3,2] - * + * * Follow up: Recursive solution is trivial, could you do it iteratively? - * + * */ pub struct Solution {} // submission codes start here -use super::util::tree::{TreeNode, to_tree}; -use std::rc::Rc; +use super::util::tree::{to_tree, TreeNode}; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn inorder_traversal(root: Option>>) -> Vec { let mut res = Vec::new(); - Solution::inorder_traverse(root.as_ref(), &mut (|v| {res.push(v)})); + Solution::inorder_traverse(root.as_ref(), &mut (|v| res.push(v))); res } @@ -50,12 +50,12 @@ mod tests { #[test] fn test_94() { assert_eq!( - Solution::inorder_traversal(tree![1,null,2,3]), - vec![1,3,2] + Solution::inorder_traversal(tree![1, null, 2, 3]), + vec![1, 3, 2] ); assert_eq!( - Solution::inorder_traversal(tree![1,2,3,4,5,6,7]), - vec![4,2,5,1,6,3,7] + Solution::inorder_traversal(tree![1, 2, 3, 4, 5, 6, 7]), + vec![4, 2, 5, 1, 6, 3, 7] ); } } diff --git a/src/n0095_unique_binary_search_trees_ii.rs b/src/n0095_unique_binary_search_trees_ii.rs index 1a60cd60..3ab366e4 100644 --- a/src/n0095_unique_binary_search_trees_ii.rs +++ b/src/n0095_unique_binary_search_trees_ii.rs @@ -2,10 +2,10 @@ * [95] Unique Binary Search Trees II * * Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. - * + * * Example: - * - * + * + * * Input: 3 * Output: * [ @@ -17,7 +17,7 @@ * ] * Explanation: * The above output corresponds to the 5 unique BST's shown below: - * + * * 1 3 3 2 1 * \ / / / \ \ * 3 2 1 1 3 2 @@ -48,19 +48,23 @@ pub struct Solution {} / \ 2 4 */ -use super::util::tree::{TreeNode, to_tree}; -use std::rc::Rc; +use super::util::tree::{to_tree, TreeNode}; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn generate_trees(n: i32) -> Vec>>> { if n < 1 { return vec![]; } let mut res = vec![Some(Rc::new(RefCell::new(TreeNode::new(1))))]; - for val in 2..n+1 { + for val in 2..n + 1 { let mut next = Vec::new(); for root in res.into_iter() { - let mut dummy = Some(Rc::new(RefCell::new(TreeNode{val: 0, left: None, right: None}))); + let mut dummy = Some(Rc::new(RefCell::new(TreeNode { + val: 0, + left: None, + right: None, + }))); let mut parent = dummy.as_ref().unwrap().clone(); let mut node = root; // we know that val is larger than all the elements in the tree @@ -78,6 +82,5 @@ mod tests { use super::*; #[test] - fn test_95() { - } + fn test_95() {} } diff --git a/src/n0096_unique_binary_search_trees.rs b/src/n0096_unique_binary_search_trees.rs index f8cbe805..7124a2bf 100644 --- a/src/n0096_unique_binary_search_trees.rs +++ b/src/n0096_unique_binary_search_trees.rs @@ -2,22 +2,22 @@ * [96] Unique Binary Search Trees * * Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? - * + * * Example: - * - * + * + * * Input: 3 * Output: 5 * Explanation: * Given n = 3, there are a total of 5 unique BST's: - * + * * 1 3 3 2 1 * \ / / / \ \ * 3 2 1 1 3 2 * / / \ \ * 2 1 2 3 - * - * + * + * */ pub struct Solution {} @@ -36,6 +36,5 @@ mod tests { use super::*; #[test] - fn test_96() { - } + fn test_96() {} } diff --git a/src/n0097_interleaving_string.rs b/src/n0097_interleaving_string.rs index 50616f20..5741bb7c 100644 --- a/src/n0097_interleaving_string.rs +++ b/src/n0097_interleaving_string.rs @@ -2,21 +2,21 @@ * [97] Interleaving String * * Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. - * + * * Example 1: - * - * + * + * * Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" * Output: true - * - * + * + * * Example 2: - * - * + * + * * Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" * Output: false - * - * + * + * */ pub struct Solution {} @@ -24,33 +24,58 @@ pub struct Solution {} // DFS with memorization /* - 思路: DFS, 三个指针 i,j,k 分别指向 s1, s2, s3 已经消费到的 char 位置, 下一个可以走的路径是 s3 当前消费到的 char 值 +思路: DFS, 三个指针 i,j,k 分别指向 s1, s2, s3 已经消费到的 char 位置, 下一个可以走的路径是 s3 当前消费到的 char 值 - 如 aaaaaas aaaaaaaw aaaaaaaaaaaaaasw - 那么第一步可以从 s1 或 s2 取一个 char, 用 DFS 的方式搜索整个解空间 +如 aaaaaas aaaaaaaw aaaaaaaaaaaaaasw +那么第一步可以从 s1 或 s2 取一个 char, 用 DFS 的方式搜索整个解空间 - 优化: 直接 DFS 非常慢, 还是上面的例子, 最差情况是大量重复字符, 时间复杂度直接是 2^(M+N), 优化方式借鉴 DP 经常用到的 - memorize, 使用一个二维数组缓存每一对遍历过的 i,j 最后是否能产生合法的 interleaving. +优化: 直接 DFS 非常慢, 还是上面的例子, 最差情况是大量重复字符, 时间复杂度直接是 2^(M+N), 优化方式借鉴 DP 经常用到的 +memorize, 使用一个二维数组缓存每一对遍历过的 i,j 最后是否能产生合法的 interleaving. - 优化后通过缓存剪除的路径比较难分析, 但很显然能知道最差情况也只需要将所有 M*N 的组合进行标记, 因此最差时间复杂度 O(M*N) - 空间复杂度 O(M*N) - */ +优化后通过缓存剪除的路径比较难分析, 但很显然能知道最差情况也只需要将所有 M*N 的组合进行标记, 因此最差时间复杂度 O(M*N) +空间复杂度 O(M*N) +*/ impl Solution { pub fn is_interleave(s1: String, s2: String, s3: String) -> bool { - let mut cache = vec![vec![false;s2.len()+1];s1.len()+1]; - Solution::dfs(&s1.chars().collect(), - &s2.chars().collect(), - &s3.chars().collect(), 0, 0, 0, &mut cache) + let mut cache = vec![vec![false; s2.len() + 1]; s1.len() + 1]; + Solution::dfs( + &s1.chars().collect(), + &s2.chars().collect(), + &s3.chars().collect(), + 0, + 0, + 0, + &mut cache, + ) } - fn dfs(s1: &Vec, s2: &Vec, s3: &Vec, i: usize, j: usize, k: usize, invalid: &mut Vec>) -> bool { - if invalid[i][j] { return false } - if i == s1.len() && j == s2.len() && k == s3.len() { return true } - let valid = - (i < s1.len() && k < s3.len() && s1[i] == s3[k] && Solution::dfs(s1,s2,s3,i+1,j,k+1,invalid)) || - (j < s2.len() && k < s3.len() && s2[j] == s3[k] && Solution::dfs(s1,s2,s3,i,j+1,k+1,invalid)); - if !valid { invalid[i][j] = true } + fn dfs( + s1: &Vec, + s2: &Vec, + s3: &Vec, + i: usize, + j: usize, + k: usize, + invalid: &mut Vec>, + ) -> bool { + if invalid[i][j] { + return false; + } + if i == s1.len() && j == s2.len() && k == s3.len() { + return true; + } + let valid = (i < s1.len() + && k < s3.len() + && s1[i] == s3[k] + && Solution::dfs(s1, s2, s3, i + 1, j, k + 1, invalid)) + || (j < s2.len() + && k < s3.len() + && s2[j] == s3[k] + && Solution::dfs(s1, s2, s3, i, j + 1, k + 1, invalid)); + if !valid { + invalid[i][j] = true + } valid } } @@ -63,8 +88,25 @@ mod tests { #[test] fn test_97() { - assert_eq!(Solution::is_interleave("aabcc".to_owned(), "dbbca".to_owned(), "aadbbcbcac".to_owned()), true); - assert_eq!(Solution::is_interleave("aabcc".to_owned(), "dbbca".to_owned(), "aadbbbaccc".to_owned()), false); - assert_eq!(Solution::is_interleave("a".to_owned(), "b".to_owned(), "a".to_owned()), false); + assert_eq!( + Solution::is_interleave( + "aabcc".to_owned(), + "dbbca".to_owned(), + "aadbbcbcac".to_owned() + ), + true + ); + assert_eq!( + Solution::is_interleave( + "aabcc".to_owned(), + "dbbca".to_owned(), + "aadbbbaccc".to_owned() + ), + false + ); + assert_eq!( + Solution::is_interleave("a".to_owned(), "b".to_owned(), "a".to_owned()), + false + ); } } diff --git a/src/n0098_validate_binary_search_tree.rs b/src/n0098_validate_binary_search_tree.rs index 89f691f0..fcb359ee 100644 --- a/src/n0098_validate_binary_search_tree.rs +++ b/src/n0098_validate_binary_search_tree.rs @@ -2,28 +2,28 @@ * [98] Validate Binary Search Tree * * Given a binary tree, determine if it is a valid binary search tree (BST). - * + * * Assume a BST is defined as follows: - * - * + * + * * The left subtree of a node contains only nodes with keys less than the node's key. * The right subtree of a node contains only nodes with keys greater than the node's key. * Both the left and right subtrees must also be binary search trees. - * - * + * + * * Example 1: - * - * + * + * * Input: * 2 * / \ * 1 3 * Output: true - * - * + * + * * Example 2: - * - * + * + * * 5 * / \ * 1 4 @@ -32,38 +32,41 @@ * Output: false * Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value * is 5 but its right child's value is 4. - * - * + * + * */ pub struct Solution {} // submission codes start here // Definition for a binary tree node. -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn is_valid_bst(root: Option>>) -> bool { let mut vec = vec![]; Solution::preorder_traverse(root.as_ref(), &mut vec) } - fn preorder_traverse(root: Option<&Rc>>, formers: &mut Vec<(i32,i32)>) -> bool { + fn preorder_traverse( + root: Option<&Rc>>, + formers: &mut Vec<(i32, i32)>, + ) -> bool { if let Some(node) = root { let root_val = root.as_ref().unwrap().borrow().val; for former in formers.iter() { - if (former.0 < 0 && root_val >= former.1) || - (former.0 > 0 && root_val <= former.1) { - return false + if (former.0 < 0 && root_val >= former.1) || (former.0 > 0 && root_val <= former.1) + { + return false; } } let mut to_right = formers.clone(); formers.push((-1, root_val)); to_right.push((1, root_val)); - Solution::preorder_traverse(node.borrow().left.as_ref(), formers) && - Solution::preorder_traverse(node.borrow().right.as_ref(), &mut to_right) + Solution::preorder_traverse(node.borrow().left.as_ref(), formers) + && Solution::preorder_traverse(node.borrow().right.as_ref(), &mut to_right) } else { true } @@ -78,8 +81,14 @@ mod tests { #[test] fn test_98() { - assert_eq!(Solution::is_valid_bst(tree![5,1,4,null,null,3,6]), false); - assert_eq!(Solution::is_valid_bst(tree![2,1,3]), true); - assert_eq!(Solution::is_valid_bst(tree![10,5,15,null,null,6,20]), false); + assert_eq!( + Solution::is_valid_bst(tree![5, 1, 4, null, null, 3, 6]), + false + ); + assert_eq!(Solution::is_valid_bst(tree![2, 1, 3]), true); + assert_eq!( + Solution::is_valid_bst(tree![10, 5, 15, null, null, 6, 20]), + false + ); } } diff --git a/src/n0099_recover_binary_search_tree.rs b/src/n0099_recover_binary_search_tree.rs index cec4ec60..8bc39b3d 100644 --- a/src/n0099_recover_binary_search_tree.rs +++ b/src/n0099_recover_binary_search_tree.rs @@ -2,60 +2,60 @@ * [99] Recover Binary Search Tree * * Two elements of a binary search tree (BST) are swapped by mistake. - * + * * Recover the tree without changing its structure. - * + * * Example 1: - * - * + * + * * Input: [1,3,null,null,2] - * + * * 1 * / * 3 * \ * 2 - * + * * Output: [3,1,null,null,2] - * + * * 3 * / * 1 * \ * 2 - * - * + * + * * Example 2: - * - * + * + * * Input: [3,1,4,null,null,2] - * + * * 3 * / \ * 1 4 * / * 2 - * + * * Output: [2,1,4,null,null,3] - * + * * 2 * / \ * 1 4 * / * 3 - * - * + * + * * Follow up: - * - * + * + * * A solution using O(n) space is pretty straight forward. * Could you devise a constant space solution? - * - * + * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -81,15 +81,20 @@ use super::util::tree::{TreeNode, to_tree}; 这个办法时间复杂度 O(N), 空间 O(1). 题解就用 Bottom-up 来写. */ -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn recover_tree(root: &mut Option>>) { Solution::recover_helper(root.as_ref()); } - fn recover_helper(root: Option<&Rc>>) - -> (Option>>, Option>>, bool) { + fn recover_helper( + root: Option<&Rc>>, + ) -> ( + Option>>, + Option>>, + bool, + ) { if let Some(node) = root { let (l_min, l_max, l_flag) = Solution::recover_helper(node.borrow().left.as_ref()); let (r_min, r_max, r_flag) = Solution::recover_helper(node.borrow().right.as_ref()); @@ -103,17 +108,32 @@ impl Solution { // invalid sub-tree found, do swap if l_err || r_err { if l_err && r_err { - } else if l_err { - std::mem::swap(&mut l_max.unwrap().borrow_mut().val, &mut node.borrow_mut().val); + std::mem::swap( + &mut l_max.unwrap().borrow_mut().val, + &mut node.borrow_mut().val, + ); } else if r_err { - std::mem::swap(&mut r_min.unwrap().borrow_mut().val, &mut node.borrow_mut().val) + std::mem::swap( + &mut r_min.unwrap().borrow_mut().val, + &mut node.borrow_mut().val, + ) } return (None, None, true); } - (if l_min.is_some() { l_min } else { Some(node.clone()) }, - if r_max.is_some() { r_max } else { Some(node.clone()) }, - false) + ( + if l_min.is_some() { + l_min + } else { + Some(node.clone()) + }, + if r_max.is_some() { + r_max + } else { + Some(node.clone()) + }, + false, + ) } else { (None, None, false) } @@ -128,12 +148,12 @@ mod tests { #[test] fn test_99() { - let mut tree = tree![3,1,4,null,null,2]; + let mut tree = tree![3, 1, 4, null, null, 2]; Solution::recover_tree(&mut tree); - assert_eq!(tree, tree![2,1,4,null,null,3]); + assert_eq!(tree, tree![2, 1, 4, null, null, 3]); - let mut tree = tree![2,6,5,null,null,3,1,null,4]; + let mut tree = tree![2, 6, 5, null, null, 3, 1, null, 4]; Solution::recover_tree(&mut tree); - assert_eq!(tree, tree![2,1,5,null,null,3,6,null,4]); + assert_eq!(tree, tree![2, 1, 5, null, null, 3, 6, null, 4]); } } diff --git a/src/n0100_same_tree.rs b/src/n0100_same_tree.rs index f5f0136c..51b7ad79 100644 --- a/src/n0100_same_tree.rs +++ b/src/n0100_same_tree.rs @@ -2,54 +2,57 @@ * [100] Same Tree * * Given two binary trees, write a function to check if they are the same or not. - * + * * Two binary trees are considered the same if they are structurally identical and the nodes have the same value. - * + * * Example 1: - * - * + * + * * Input: 1 1 * / \ / \ * 2 3 2 3 - * + * * [1,2,3], [1,2,3] - * + * * Output: true - * - * + * + * * Example 2: - * - * + * + * * Input: 1 1 * / \ * 2 2 - * + * * [1,2], [1,null,2] - * + * * Output: false - * - * + * + * * Example 3: - * - * + * + * * Input: 1 1 * / \ / \ * 2 1 1 2 - * + * * [1,2,1], [1,1,2] - * + * * Output: false - * - * + * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { - pub fn is_same_tree(p: Option>>, q: Option>>) -> bool { + pub fn is_same_tree( + p: Option>>, + q: Option>>, + ) -> bool { p == q } } @@ -62,6 +65,9 @@ mod tests { #[test] fn test_100() { - assert_eq!(Solution::is_same_tree(tree![1,2,3,4,null,5], tree![1,2,3,4,null,5]), true) + assert_eq!( + Solution::is_same_tree(tree![1, 2, 3, 4, null, 5], tree![1, 2, 3, 4, null, 5]), + true + ) } } diff --git a/src/n0101_symmetric_tree.rs b/src/n0101_symmetric_tree.rs index e4a3aadb..d341ff34 100644 --- a/src/n0101_symmetric_tree.rs +++ b/src/n0101_symmetric_tree.rs @@ -2,52 +2,63 @@ * [101] Symmetric Tree * * Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). - * - * + * + * * For example, this binary tree [1,2,2,3,4,4,3] is symmetric: - * + * * 1 * / \ * 2 2 * / \ / \ * 3 4 4 3 - * - * - * + * + * + * * But the following [1,2,2,null,3,null,3] is not:
- * + * * 1 * / \ * 2 2 * \ \ * 3 3 - * - * - * - * + * + * + * + * * Note:
* Bonus points if you could solve it both recursively and iteratively. - * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn is_symmetric(root: Option>>) -> bool { - Solution::symmetric_helper(root.as_ref().and_then(|v| v.borrow().left.clone()), - root.as_ref().and_then(|v| v.borrow().right.clone())) + Solution::symmetric_helper( + root.as_ref().and_then(|v| v.borrow().left.clone()), + root.as_ref().and_then(|v| v.borrow().right.clone()), + ) } - fn symmetric_helper(left: Option>>, right: Option>>) -> bool { + fn symmetric_helper( + left: Option>>, + right: Option>>, + ) -> bool { match (left, right) { (Some(left), Some(right)) => { - left.borrow().val == right.borrow().val && - Solution::symmetric_helper(left.borrow().left.clone(), right.borrow().right.clone()) && - Solution::symmetric_helper(left.borrow().right.clone(), right.borrow().left.clone()) + left.borrow().val == right.borrow().val + && Solution::symmetric_helper( + left.borrow().left.clone(), + right.borrow().right.clone(), + ) + && Solution::symmetric_helper( + left.borrow().right.clone(), + right.borrow().left.clone(), + ) } (None, None) => true, _ => false, @@ -63,8 +74,11 @@ mod tests { #[test] fn test_101() { - assert_eq!(Solution::is_symmetric(tree![1,2,2,3,4,4,3]), true); - assert_eq!(Solution::is_symmetric(tree![1,2,2,null,3,null,3]), false); + assert_eq!(Solution::is_symmetric(tree![1, 2, 2, 3, 4, 4, 3]), true); + assert_eq!( + Solution::is_symmetric(tree![1, 2, 2, null, 3, null, 3]), + false + ); assert_eq!(Solution::is_symmetric(tree![]), true); } } diff --git a/src/n0102_binary_tree_level_order_traversal.rs b/src/n0102_binary_tree_level_order_traversal.rs index 603cb870..6fdabf6e 100644 --- a/src/n0102_binary_tree_level_order_traversal.rs +++ b/src/n0102_binary_tree_level_order_traversal.rs @@ -2,49 +2,51 @@ * [102] Binary Tree Level Order Traversal * * Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). - * - * + * + * * For example:
* Given binary tree [3,9,20,null,null,15,7],
- * + * * 3 * / \ * 9 20 * / \ * 15 7 - * - * - * + * + * + * * return its level order traversal as:
- * + * * [ * [3], * [9,20], * [15,7] * ] - * - * + * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; use std::collections::VecDeque; +use std::rc::Rc; impl Solution { pub fn level_order(root: Option>>) -> Vec> { let mut res = Vec::new(); let mut current_level = 0; - if root.is_none() { return res } + if root.is_none() { + return res; + } let mut deq = VecDeque::new(); deq.push_back((0, root.clone())); let mut vec = Vec::new(); while !deq.is_empty() { if let Some((level, Some(node))) = deq.pop_front() { - deq.push_back((level+1, node.borrow().left.clone())); - deq.push_back((level+1, node.borrow().right.clone())); + deq.push_back((level + 1, node.borrow().left.clone())); + deq.push_back((level + 1, node.borrow().right.clone())); if level > current_level { res.push(vec); vec = Vec::new(); @@ -53,7 +55,9 @@ impl Solution { vec.push(node.borrow().val); } } - if !vec.is_empty() { res.push(vec) } + if !vec.is_empty() { + res.push(vec) + } res } } @@ -67,12 +71,8 @@ mod tests { #[test] fn test_102() { assert_eq!( - Solution::level_order(tree![3,9,20,null,null,15,7]), - vec![ - vec![3], - vec![9,20], - vec![15,7] - ] + Solution::level_order(tree![3, 9, 20, null, null, 15, 7]), + vec![vec![3], vec![9, 20], vec![15, 7]] ); } } diff --git a/src/n0103_binary_tree_zigzag_level_order_traversal.rs b/src/n0103_binary_tree_zigzag_level_order_traversal.rs index c9d449ef..ce31b6b8 100644 --- a/src/n0103_binary_tree_zigzag_level_order_traversal.rs +++ b/src/n0103_binary_tree_zigzag_level_order_traversal.rs @@ -2,42 +2,44 @@ * [103] Binary Tree Zigzag Level Order Traversal * * Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). - * - * + * + * * For example:
* Given binary tree [3,9,20,null,null,15,7],
- * + * * 3 * / \ * 9 20 * / \ * 15 7 - * - * - * + * + * + * * return its zigzag level order traversal as:
- * + * * [ * [3], * [20,9], * [15,7] * ] - * - * + * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; use std::collections::VecDeque; +use std::rc::Rc; impl Solution { pub fn zigzag_level_order(root: Option>>) -> Vec> { let mut res = Vec::new(); let mut current_level = 0; - if root.is_none() { return res } + if root.is_none() { + return res; + } let mut deq = VecDeque::new(); deq.push_back((0, root.clone())); let mut vec = Vec::new(); @@ -75,12 +77,8 @@ mod tests { #[test] fn test_103() { assert_eq!( - Solution::zigzag_level_order(tree![3,9,20,null,null,15,7]), - vec![ - vec![3], - vec![20,9], - vec![15,7] - ] + Solution::zigzag_level_order(tree![3, 9, 20, null, null, 15, 7]), + vec![vec![3], vec![20, 9], vec![15, 7]] ); } } diff --git a/src/n0104_maximum_depth_of_binary_tree.rs b/src/n0104_maximum_depth_of_binary_tree.rs index f880b095..c5faf233 100644 --- a/src/n0104_maximum_depth_of_binary_tree.rs +++ b/src/n0104_maximum_depth_of_binary_tree.rs @@ -2,32 +2,32 @@ * [104] Maximum Depth of Binary Tree * * Given a binary tree, find its maximum depth. - * + * * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. - * + * * Note: A leaf is a node with no children. - * + * * Example: - * + * * Given binary tree [3,9,20,null,null,15,7], - * - * + * + * * 3 * / \ * 9 20 * / \ * 15 7 - * + * * return its depth = 3. - * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn max_depth(root: Option>>) -> i32 { let mut max = 0; @@ -53,6 +53,6 @@ mod tests { #[test] fn test_104() { assert_eq!(Solution::max_depth(tree![]), 0); - assert_eq!(Solution::max_depth(tree![3,9,20,null,null,15,7]), 3); + assert_eq!(Solution::max_depth(tree![3, 9, 20, null, null, 15, 7]), 3); } } diff --git a/src/n0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs b/src/n0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs index 71521287..611725de 100644 --- a/src/n0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs +++ b/src/n0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs @@ -2,45 +2,47 @@ * [105] Construct Binary Tree from Preorder and Inorder Traversal * * Given preorder and inorder traversal of a tree, construct the binary tree. - * + * * Note:
* You may assume that duplicates do not exist in the tree. - * + * * For example, given - * - * + * + * * preorder = [3,9,20,15,7] * inorder = [9,3,15,20,7] - * + * * Return the following binary tree: - * - * + * + * * 3 * / \ * 9 20 * / \ * 15 7 - * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn build_tree(preorder: Vec, inorder: Vec) -> Option>> { Solution::build_tree_helper(&preorder[..], &inorder[..]) } fn build_tree_helper(preorder: &[i32], inorder: &[i32]) -> Option>> { - if preorder.is_empty() { return None } + if preorder.is_empty() { + return None; + } let root_idx = inorder.iter().position(|&v| v == preorder[0]).unwrap(); - Some(Rc::new(RefCell::new(TreeNode{ + Some(Rc::new(RefCell::new(TreeNode { val: preorder[0], - left: Solution::build_tree_helper(&preorder[1..root_idx+1], &inorder[0..root_idx]), - right: Solution::build_tree_helper(&preorder[root_idx+1..], &inorder[root_idx+1..]), + left: Solution::build_tree_helper(&preorder[1..root_idx + 1], &inorder[0..root_idx]), + right: Solution::build_tree_helper(&preorder[root_idx + 1..], &inorder[root_idx + 1..]), }))) } } @@ -53,8 +55,14 @@ mod tests { #[test] fn test_105() { - assert_eq!(Solution::build_tree(vec![3,9,20,15,7], vec![9,3,15,20,7]), tree![3,9,20,null,null,15,7]); - assert_eq!(Solution::build_tree(vec![3,20,7], vec![3,20,7]), tree![3,null,20,null,7]); + assert_eq!( + Solution::build_tree(vec![3, 9, 20, 15, 7], vec![9, 3, 15, 20, 7]), + tree![3, 9, 20, null, null, 15, 7] + ); + assert_eq!( + Solution::build_tree(vec![3, 20, 7], vec![3, 20, 7]), + tree![3, null, 20, null, 7] + ); assert_eq!(Solution::build_tree(vec![], vec![]), tree![]); } } diff --git a/src/n0107_binary_tree_level_order_traversal_ii.rs b/src/n0107_binary_tree_level_order_traversal_ii.rs index be2f6fc1..42855964 100644 --- a/src/n0107_binary_tree_level_order_traversal_ii.rs +++ b/src/n0107_binary_tree_level_order_traversal_ii.rs @@ -2,49 +2,51 @@ * [107] Binary Tree Level Order Traversal II * * Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). - * - * + * + * * For example:
* Given binary tree [3,9,20,null,null,15,7],
- * + * * 3 * / \ * 9 20 * / \ * 15 7 - * - * - * + * + * + * * return its bottom-up level order traversal as:
- * + * * [ * [15,7], * [9,20], * [3] * ] - * - * + * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; use std::collections::VecDeque; +use std::rc::Rc; impl Solution { pub fn level_order_bottom(root: Option>>) -> Vec> { let mut res = Vec::new(); let mut current_level = 0; - if root.is_none() { return res } + if root.is_none() { + return res; + } let mut deq = VecDeque::new(); deq.push_back((0, root.clone())); let mut vec = Vec::new(); while !deq.is_empty() { if let Some((level, Some(node))) = deq.pop_front() { - deq.push_back((level+1, node.borrow().left.clone())); - deq.push_back((level+1, node.borrow().right.clone())); + deq.push_back((level + 1, node.borrow().left.clone())); + deq.push_back((level + 1, node.borrow().right.clone())); if level > current_level { res.push(vec); vec = Vec::new(); @@ -53,7 +55,9 @@ impl Solution { vec.push(node.borrow().val); } } - if !vec.is_empty() { res.push(vec) } + if !vec.is_empty() { + res.push(vec) + } res.reverse(); res } @@ -68,12 +72,8 @@ mod tests { #[test] fn test_107() { assert_eq!( - Solution::level_order_bottom(tree![3,9,20,null,null,15,7]), - vec![ - vec![15,7], - vec![9,20], - vec![3], - ] + Solution::level_order_bottom(tree![3, 9, 20, null, null, 15, 7]), + vec![vec![15, 7], vec![9, 20], vec![3],] ); } } diff --git a/src/n0108_convert_sorted_array_to_binary_search_tree.rs b/src/n0108_convert_sorted_array_to_binary_search_tree.rs index 0a6d6dc7..4da33781 100644 --- a/src/n0108_convert_sorted_array_to_binary_search_tree.rs +++ b/src/n0108_convert_sorted_array_to_binary_search_tree.rs @@ -2,42 +2,44 @@ * [108] Convert Sorted Array to Binary Search Tree * * Given an array where elements are sorted in ascending order, convert it to a height balanced BST. - * + * * For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. - * + * * Example: - * - * + * + * * Given the sorted array: [-10,-3,0,5,9], - * + * * One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: - * + * * 0 * / \ * -3 9 * / / * -10 5 - * - * + * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn sorted_array_to_bst(nums: Vec) -> Option>> { Solution::bst_helper(&nums[..]) } fn bst_helper(nums: &[i32]) -> Option>> { - if nums.is_empty() { return None } - Some(Rc::new(RefCell::new(TreeNode{ + if nums.is_empty() { + return None; + } + Some(Rc::new(RefCell::new(TreeNode { val: nums[nums.len() / 2], - left: Solution::bst_helper(&nums[0..(nums.len()/2)]), - right: Solution::bst_helper(&nums[(nums.len()/2+1)..]), + left: Solution::bst_helper(&nums[0..(nums.len() / 2)]), + right: Solution::bst_helper(&nums[(nums.len() / 2 + 1)..]), }))) } } @@ -50,7 +52,10 @@ mod tests { #[test] fn test_108() { - assert_eq!(Solution::sorted_array_to_bst(vec![-10,-3,0,5,9]), tree![0,-3,9,-10,null,5]); + assert_eq!( + Solution::sorted_array_to_bst(vec![-10, -3, 0, 5, 9]), + tree![0, -3, 9, -10, null, 5] + ); assert_eq!(Solution::sorted_array_to_bst(vec![]), tree![]); } } diff --git a/src/n0109_convert_sorted_list_to_binary_search_tree.rs b/src/n0109_convert_sorted_list_to_binary_search_tree.rs index 59d3233e..072c6eac 100644 --- a/src/n0109_convert_sorted_list_to_binary_search_tree.rs +++ b/src/n0109_convert_sorted_list_to_binary_search_tree.rs @@ -2,32 +2,32 @@ * [109] Convert Sorted List to Binary Search Tree * * Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. - * + * * For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. - * + * * Example: - * - * + * + * * Given the sorted linked list: [-10,-3,0,5,9], - * + * * One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: - * + * * 0 * / \ * -3 9 * / / * -10 5 - * - * + * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; -use super::util::tree::{TreeNode, to_tree}; +use super::util::linked_list::{to_list, ListNode}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn sorted_list_to_bst(head: Option>) -> Option>> { let mut arr = Vec::new(); @@ -40,11 +40,13 @@ impl Solution { } fn bst_helper(nums: &[i32]) -> Option>> { - if nums.is_empty() { return None } - Some(Rc::new(RefCell::new(TreeNode{ + if nums.is_empty() { + return None; + } + Some(Rc::new(RefCell::new(TreeNode { val: nums[nums.len() / 2], - left: Solution::bst_helper(&nums[0..(nums.len()/2)]), - right: Solution::bst_helper(&nums[(nums.len()/2+1)..]), + left: Solution::bst_helper(&nums[0..(nums.len() / 2)]), + right: Solution::bst_helper(&nums[(nums.len() / 2 + 1)..]), }))) } } @@ -57,6 +59,9 @@ mod tests { #[test] fn test_109() { - assert_eq!(Solution::sorted_list_to_bst(linked![-10,-3,0,5,9]), tree![0,-3,9,-10,null,5]); + assert_eq!( + Solution::sorted_list_to_bst(linked![-10, -3, 0, 5, 9]), + tree![0, -3, 9, -10, null, 5] + ); } } diff --git a/src/n0110_balanced_binary_tree.rs b/src/n0110_balanced_binary_tree.rs index 8a1b8582..68e1b2ad 100644 --- a/src/n0110_balanced_binary_tree.rs +++ b/src/n0110_balanced_binary_tree.rs @@ -2,31 +2,31 @@ * [110] Balanced Binary Tree * * Given a binary tree, determine if it is height-balanced. - * + * * For this problem, a height-balanced binary tree is defined as: - * + * *
* a binary tree in which the depth of the two subtrees of every node never differ by more than 1. *
- * + * * Example 1: - * + * * Given the following tree [3,9,20,null,null,15,7]: - * - * + * + * * 3 * / \ * 9 20 * / \ * 15 7 - * + * * Return true.
*
* Example 2: - * + * * Given the following tree [1,2,2,3,3,null,null,4,4]: - * - * + * + * * 1 * / \ * 2 2 @@ -34,18 +34,18 @@ * 3 3 * / \ * 4 4 - * - * + * + * * Return false. - * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn is_balanced(root: Option>>) -> bool { Solution::balanced_helper(root.as_ref()).is_some() @@ -53,13 +53,16 @@ impl Solution { fn balanced_helper(root: Option<&Rc>>) -> Option { if let Some(node) = root { - let pair = (Solution::balanced_helper(node.borrow().left.as_ref()), Solution::balanced_helper(node.borrow().right.as_ref())); + let pair = ( + Solution::balanced_helper(node.borrow().left.as_ref()), + Solution::balanced_helper(node.borrow().right.as_ref()), + ); match pair { (Some(left), Some(right)) => { if i32::abs(left - right) < 2 { return Some(i32::max(left, right) + 1); } else { - return None + return None; } } _ => return None, @@ -79,7 +82,13 @@ mod tests { #[test] fn test_110() { assert_eq!(Solution::is_balanced(tree![]), true); - assert_eq!(Solution::is_balanced(tree![3,9,20,null,null,15,7]), true); - assert_eq!(Solution::is_balanced(tree![1,2,2,3,3,null,null,4,4]), false); + assert_eq!( + Solution::is_balanced(tree![3, 9, 20, null, null, 15, 7]), + true + ); + assert_eq!( + Solution::is_balanced(tree![1, 2, 2, 3, 3, null, null, 4, 4]), + false + ); } } diff --git a/src/n0111_minimum_depth_of_binary_tree.rs b/src/n0111_minimum_depth_of_binary_tree.rs index 4ce67d40..f537c316 100644 --- a/src/n0111_minimum_depth_of_binary_tree.rs +++ b/src/n0111_minimum_depth_of_binary_tree.rs @@ -2,45 +2,47 @@ * [111] Minimum Depth of Binary Tree * * Given a binary tree, find its minimum depth. - * + * * The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. - * + * * Note: A leaf is a node with no children. - * + * * Example: - * + * * Given binary tree [3,9,20,null,null,15,7], - * - * + * + * * 3 * / \ * 9 20 * / \ * 15 7 - * + * * return its minimum depth = 2. - * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; use std::collections::VecDeque; +use std::rc::Rc; impl Solution { pub fn min_depth(root: Option>>) -> i32 { - if root.is_none() { return 0 } + if root.is_none() { + return 0; + } let mut deq = VecDeque::new(); deq.push_back((1, root.clone())); while !deq.is_empty() { if let Some((level, Some(node))) = deq.pop_front() { if node.borrow().left.is_none() && node.borrow().right.is_none() { - return level + return level; } - deq.push_back((level+1, node.borrow().left.clone())); - deq.push_back((level+1, node.borrow().right.clone())); + deq.push_back((level + 1, node.borrow().left.clone())); + deq.push_back((level + 1, node.borrow().right.clone())); } } 0 @@ -55,6 +57,6 @@ mod tests { #[test] fn test_111() { - assert_eq!(Solution::min_depth(tree![3,9,20,null,null,15,7]), 2); + assert_eq!(Solution::min_depth(tree![3, 9, 20, null, null, 15, 7]), 2); } } diff --git a/src/n0112_path_sum.rs b/src/n0112_path_sum.rs index f8430c87..72e34da0 100644 --- a/src/n0112_path_sum.rs +++ b/src/n0112_path_sum.rs @@ -2,14 +2,14 @@ * [112] Path Sum * * Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. - * + * * Note: A leaf is a node with no children. - * + * * Example: - * + * * Given the below binary tree and sum = 22, - * - * + * + * * 5 * / \ * 4 8 @@ -17,32 +17,40 @@ * 11 13 4 * / \ \ * 7 2 1 - * - * + * + * * return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. - * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; use std::collections::VecDeque; +use std::rc::Rc; impl Solution { pub fn has_path_sum(root: Option>>, sum: i32) -> bool { - if root.is_none() { return false } + if root.is_none() { + return false; + } let mut deq = VecDeque::new(); deq.push_back((0, root.unwrap().clone())); while !deq.is_empty() { if let Some((acc, node)) = deq.pop_front() { let acc = acc + node.borrow().val; if node.borrow().left.is_none() && node.borrow().right.is_none() { - if acc == sum { return true } + if acc == sum { + return true; + } } else { - if node.borrow().left.is_some() { deq.push_back((acc, node.borrow().left.as_ref().unwrap().clone())) }; - if node.borrow().right.is_some() { deq.push_back((acc, node.borrow().right.as_ref().unwrap().clone())) }; + if node.borrow().left.is_some() { + deq.push_back((acc, node.borrow().left.as_ref().unwrap().clone())) + }; + if node.borrow().right.is_some() { + deq.push_back((acc, node.borrow().right.as_ref().unwrap().clone())) + }; } } } @@ -58,6 +66,12 @@ mod tests { #[test] fn test_112() { - assert_eq!(Solution::has_path_sum(tree![5,4,8,11,null,13,4,7,2,null,null,null,1], 22), true); + assert_eq!( + Solution::has_path_sum( + tree![5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], + 22 + ), + true + ); } } diff --git a/src/n0113_path_sum_ii.rs b/src/n0113_path_sum_ii.rs index f4660555..c9914e08 100644 --- a/src/n0113_path_sum_ii.rs +++ b/src/n0113_path_sum_ii.rs @@ -2,14 +2,14 @@ * [113] Path Sum II * * Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. - * + * * Note: A leaf is a node with no children. - * + * * Example: - * + * * Given the below binary tree and sum = 22, - * - * + * + * * 5 * / \ * 4 8 @@ -17,30 +17,32 @@ * 11 13 4 * / \ / \ * 7 2 5 1 - * - * + * + * * Return: - * - * + * + * * [ * [5,4,11,2], * [5,8,4,5] * ] - * - * + * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; use std::collections::VecDeque; +use std::rc::Rc; impl Solution { pub fn path_sum(root: Option>>, sum: i32) -> Vec> { let mut res = Vec::new(); - if root.is_none() { return res } + if root.is_none() { + return res; + } let mut deq = VecDeque::new(); deq.push_back((0, Vec::new(), root.clone())); while !deq.is_empty() { @@ -52,8 +54,12 @@ impl Solution { res.push(vec); } } else { - if node.borrow().left.is_some() { deq.push_back((acc, vec.clone(), node.borrow().left.clone())); } - if node.borrow().right.is_some() { deq.push_back((acc, vec.clone(), node.borrow().right.clone())); } + if node.borrow().left.is_some() { + deq.push_back((acc, vec.clone(), node.borrow().left.clone())); + } + if node.borrow().right.is_some() { + deq.push_back((acc, vec.clone(), node.borrow().right.clone())); + } } } } @@ -70,11 +76,8 @@ mod tests { #[test] fn test_113() { assert_eq!( - Solution::path_sum(tree![5,4,8,11,null,13,4,7,2,null,null,5,1], 22), - vec![ - vec![5,4,11,2], - vec![5,8,4,5] - ] + Solution::path_sum(tree![5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1], 22), + vec![vec![5, 4, 11, 2], vec![5, 8, 4, 5]] ) } } diff --git a/src/n0114_flatten_binary_tree_to_linked_list.rs b/src/n0114_flatten_binary_tree_to_linked_list.rs index 385c89a1..2b46cd42 100644 --- a/src/n0114_flatten_binary_tree_to_linked_list.rs +++ b/src/n0114_flatten_binary_tree_to_linked_list.rs @@ -2,20 +2,20 @@ * [114] Flatten Binary Tree to Linked List * * Given a binary tree, flatten it to a linked list in-place. - * + * * For example, given the following tree: - * - * + * + * * 1 * / \ * 2 5 * / \ \ * 3 4 6 - * - * + * + * * The flattened tree should look like: - * - * + * + * * 1 * \ * 2 @@ -27,16 +27,16 @@ * 5 * \ * 6 - * - * + * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn flatten(root: &mut Option>>) { Solution::flatten_helper(root.clone()); @@ -72,16 +72,16 @@ mod tests { #[test] fn test_114() { - let mut tree = tree![1,2,5,3,4,null,6]; + let mut tree = tree![1, 2, 5, 3, 4, null, 6]; Solution::flatten(&mut tree); - assert_eq!(tree, tree![1,null,2,null,3,null,4,null,5,null,6]); + assert_eq!(tree, tree![1, null, 2, null, 3, null, 4, null, 5, null, 6]); - let mut tree = tree![1,2,null,3]; + let mut tree = tree![1, 2, null, 3]; Solution::flatten(&mut tree); - assert_eq!(tree, tree![1,null,2,null,3]); + assert_eq!(tree, tree![1, null, 2, null, 3]); - let mut tree = tree![1,null,2,3]; + let mut tree = tree![1, null, 2, 3]; Solution::flatten(&mut tree); - assert_eq!(tree, tree![1,null,2,null,3]); + assert_eq!(tree, tree![1, null, 2, null, 3]); } } diff --git a/src/n0115_distinct_subsequences.rs b/src/n0115_distinct_subsequences.rs index efac6293..f67304f6 100644 --- a/src/n0115_distinct_subsequences.rs +++ b/src/n0115_distinct_subsequences.rs @@ -2,37 +2,37 @@ * [115] Distinct Subsequences * * Given a string S and a string T, count the number of distinct subsequences of S which equals T. - * + * * A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). - * + * * Example 1: - * - * + * + * * Input: S = "rabbbit", T = "rabbit" * Output: 3 * Explanation: - * + * * As shown below, there are 3 ways you can generate "rabbit" from S. * (The caret symbol ^ means the chosen letters) - * + * * rabbbit * ^^^^ ^^ * rabbbit * ^^ ^^^^ * rabbbit * ^^^ ^^^ - * - * + * + * * Example 2: - * - * + * + * * Input: S = "babgbag", T = "bag" * Output: 5 * Explanation: - * + * * As shown below, there are 5 ways you can generate "bag" from S. * (The caret symbol ^ means the chosen letters) - * + * * babgbag * ^^ ^ * babgbag @@ -43,36 +43,36 @@ * ^ ^^ * babgbag * ^^^ - * - * + * + * */ pub struct Solution {} // submission codes start here /* - 首先想到 DFS. 但这里 DFS 有重复计算, 因为我们不需要列出所有的路径, 复杂度可以考虑 "aaaaaaaaaaaaaaaaaaaa" - 里找 "aaaaaaaaa", 直接搜索的话复杂度是指数级的(阶乘), 原因很明显, 这本身是个排列组合, 可以套 combination 公式 - 20! / ((20-10)! * 10!) 得到结果是 184756 +首先想到 DFS. 但这里 DFS 有重复计算, 因为我们不需要列出所有的路径, 复杂度可以考虑 "aaaaaaaaaaaaaaaaaaaa" +里找 "aaaaaaaaa", 直接搜索的话复杂度是指数级的(阶乘), 原因很明显, 这本身是个排列组合, 可以套 combination 公式 +20! / ((20-10)! * 10!) 得到结果是 184756 - 要把复杂度从指数级降下来, 那么必须干掉重复计算, 那就想到 memorize, 想到 memorize 就想到 DP 和 Bottom-Up 递推, - 回顾一下 #62 和 #63 这两个问题 (unique paths), 使用的是Bottom-Up DP, 到达每个格子的可能路径是上下两个格子的 - 可能路径的和. 这里就跳过了很多的计算, 不需要把每条路径都遍历出来了. 在 unique paths 问题中, 到达右下角的路径数的 - 子问题是到达右下角左侧格子的路径数以及到达右下角上侧格子的路径数. 这个问题也是一样的道理, s 中找子序列 t: +要把复杂度从指数级降下来, 那么必须干掉重复计算, 那就想到 memorize, 想到 memorize 就想到 DP 和 Bottom-Up 递推, +回顾一下 #62 和 #63 这两个问题 (unique paths), 使用的是Bottom-Up DP, 到达每个格子的可能路径是上下两个格子的 +可能路径的和. 这里就跳过了很多的计算, 不需要把每条路径都遍历出来了. 在 unique paths 问题中, 到达右下角的路径数的 +子问题是到达右下角左侧格子的路径数以及到达右下角上侧格子的路径数. 这个问题也是一样的道理, s 中找子序列 t: - * s[0..i] 包含的 t 序列数就是所有 s[0..j] (j < i) 包含的 t[0..t.len()-1] 的序列数 +* s[0..i] 包含的 t 序列数就是所有 s[0..j] (j < i) 包含的 t[0..t.len()-1] 的序列数 - 以 babgbag 中找 bag 为例, 做一次 Bottom-Up 递推: +以 babgbag 中找 bag 为例, 做一次 Bottom-Up 递推: - b a b g b a g - b 1 1 1 3 找 'b' 这个子序列, 那么以 [0, 2, 4] 这三个下标结尾各有一种 - a 1 3 4 找 'ba' 这个子序列, 那么以 1 结尾有1种(0 < 1), 以 5 结尾有 3 种 (0,2,4 都 < 5) - g 1 4 5 同理, 以 3 结尾有 1 种, 以 6 结尾有 4 种, 共 5 种 + b a b g b a g +b 1 1 1 3 找 'b' 这个子序列, 那么以 [0, 2, 4] 这三个下标结尾各有一种 +a 1 3 4 找 'ba' 这个子序列, 那么以 1 结尾有1种(0 < 1), 以 5 结尾有 3 种 (0,2,4 都 < 5) +g 1 4 5 同理, 以 3 结尾有 1 种, 以 6 结尾有 4 种, 共 5 种 - 显然, 计算第 N 行时只依赖第 N-1 行的结果, 因此我们不需要存储整个矩阵, 只需要存储一行即可 +显然, 计算第 N 行时只依赖第 N-1 行的结果, 因此我们不需要存储整个矩阵, 只需要存储一行即可 - 时间复杂度是 O(M*N), 空间复杂度是 O(M) - */ +时间复杂度是 O(M*N), 空间复杂度是 O(M) +*/ impl Solution { pub fn num_distinct(s: String, t: String) -> i32 { let s = s.chars().collect::>(); @@ -82,9 +82,11 @@ impl Solution { // first char initialization if i == 0 { for i in 0..s.len() { - if ch == s[i] { cache[i] = 1 } + if ch == s[i] { + cache[i] = 1 + } } - continue + continue; } for i in 0..s.len() { let new_acc = acc + cache[i]; @@ -105,7 +107,13 @@ mod tests { #[test] fn test_115() { //assert_eq!(Solution::num_distinct("rabbbit".to_owned(), "rabbit".to_owned()), 3); - assert_eq!(Solution::num_distinct("babgbag".to_owned(), "bag".to_owned()), 5); - assert_eq!(Solution::num_distinct("aaaaaaaaaaaaaaaaaaaa".to_owned(), "aaaaaaaaaa".to_owned()), 184756); + assert_eq!( + Solution::num_distinct("babgbag".to_owned(), "bag".to_owned()), + 5 + ); + assert_eq!( + Solution::num_distinct("aaaaaaaaaaaaaaaaaaaa".to_owned(), "aaaaaaaaaa".to_owned()), + 184756 + ); } } diff --git a/src/n0118_pascals_triangle.rs b/src/n0118_pascals_triangle.rs index f6d7c124..a69d64e4 100644 --- a/src/n0118_pascals_triangle.rs +++ b/src/n0118_pascals_triangle.rs @@ -2,13 +2,13 @@ * [118] Pascal's Triangle * * Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. - * + * *
* In Pascal's triangle, each number is the sum of the two numbers directly above it. - * + * * Example: - * - * + * + * * Input: 5 * Output: * [ @@ -18,8 +18,8 @@ * [1,3,3,1], * [1,4,6,4,1] * ] - * - * + * + * */ pub struct Solution {} @@ -28,12 +28,14 @@ pub struct Solution {} impl Solution { pub fn generate(num_rows: i32) -> Vec> { let mut res = Vec::new(); - if num_rows < 1 { return res } + if num_rows < 1 { + return res; + } let mut curr = vec![1]; for _ in 0..num_rows { - let mut next = vec![1; curr.len()+1]; + let mut next = vec![1; curr.len() + 1]; for i in 1..curr.len() { - next[i] = curr[i-1] + curr[i]; + next[i] = curr[i - 1] + curr[i]; } res.push(curr); curr = next; @@ -55,10 +57,11 @@ mod tests { Solution::generate(5), vec![ vec![1], - vec![1,1], - vec![1,2,1], - vec![1,3,3,1], - vec![1,4,6,4,1] - ]); + vec![1, 1], + vec![1, 2, 1], + vec![1, 3, 3, 1], + vec![1, 4, 6, 4, 1] + ] + ); } } diff --git a/src/n0119_pascals_triangle_ii.rs b/src/n0119_pascals_triangle_ii.rs index 5d2b1dcb..5129ed5a 100644 --- a/src/n0119_pascals_triangle_ii.rs +++ b/src/n0119_pascals_triangle_ii.rs @@ -2,40 +2,40 @@ * [119] Pascal's Triangle II * * Given a non-negative index k where k ≤ 33, return the k^th index row of the Pascal's triangle. - * + * * Note that the row index starts from 0. - * + * *
* In Pascal's triangle, each number is the sum of the two numbers directly above it. - * + * * Example: - * - * + * + * * Input: 3 * Output: [1,3,3,1] - * - * + * + * * Follow up: - * + * * Could you optimize your algorithm to use only O(k) extra space? - * + * */ pub struct Solution {} // submission codes start here /* - in-place algorithm +in-place algorithm - 1 1 1 1 1 - 1 2 1 1 1 - 1 3 3 1 1 - 1 4 6 4 1 - */ +1 1 1 1 1 +1 2 1 1 1 +1 3 3 1 1 +1 4 6 4 1 +*/ impl Solution { pub fn get_row(row_index: i32) -> Vec { - let mut curr = vec![1;(row_index+1) as usize]; - for i in 0..row_index+1 { + let mut curr = vec![1; (row_index + 1) as usize]; + for i in 0..row_index + 1 { let mut prev = 1; for j in 1..i { let temp = curr[j as usize]; @@ -56,9 +56,6 @@ mod tests { #[test] fn test_119() { assert_eq!(Solution::get_row(0), vec![1]); - assert_eq!( - Solution::get_row(4), - vec![1,4,6,4,1] - ) + assert_eq!(Solution::get_row(4), vec![1, 4, 6, 4, 1]) } } diff --git a/src/n0120_triangle.rs b/src/n0120_triangle.rs index 609182ce..4a96591a 100644 --- a/src/n0120_triangle.rs +++ b/src/n0120_triangle.rs @@ -2,10 +2,10 @@ * [120] Triangle * * Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. - * + * * For example, given the following triangle - * - * + * + * * [ * [2], * [3,4], @@ -13,13 +13,13 @@ * [4,1,8,3] * ] * - * + * * The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). - * + * * Note: - * + * * Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. - * + * */ pub struct Solution {} @@ -42,7 +42,9 @@ impl Solution { prev = temp; } } - cache.into_iter().fold(i32::max_value(), |min, x| i32::min(min, x)) + cache + .into_iter() + .fold(i32::max_value(), |min, x| i32::min(min, x)) } } @@ -55,14 +57,7 @@ mod tests { #[test] fn test_120() { assert_eq!( - Solution::minimum_total( - vec![ - vec![2], - vec![3,4], - vec![6,5,7], - vec![4,1,8,3] - ] - ), + Solution::minimum_total(vec![vec![2], vec![3, 4], vec![6, 5, 7], vec![4, 1, 8, 3]]), 11 ) } diff --git a/src/n0121_best_time_to_buy_and_sell_stock.rs b/src/n0121_best_time_to_buy_and_sell_stock.rs index 51548dec..fa27fc10 100644 --- a/src/n0121_best_time_to_buy_and_sell_stock.rs +++ b/src/n0121_best_time_to_buy_and_sell_stock.rs @@ -2,28 +2,28 @@ * [121] Best Time to Buy and Sell Stock * * Say you have an array for which the i^th element is the price of a given stock on day i. - * + * * If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. - * + * * Note that you cannot sell a stock before you buy one. - * + * * Example 1: - * - * + * + * * Input: [7,1,5,3,6,4] * Output: 5 * Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. * Not 7-1 = 6, as selling price needs to be larger than buying price. - * - * + * + * * Example 2: - * - * + * + * * Input: [7,6,4,3,1] * Output: 0 * Explanation: In this case, no transaction is done, i.e. max profit = 0. - * - * + * + * */ pub struct Solution {} @@ -34,7 +34,7 @@ impl Solution { let mut max = 0; let mut curr = 0; for i in 1..prices.len() { - curr = curr + prices[i] - prices[i-1]; + curr = curr + prices[i] - prices[i - 1]; if curr <= 0 { curr = 0; } else { @@ -53,7 +53,7 @@ mod tests { #[test] fn test_121() { - assert_eq!(Solution::max_profit(vec![7,1,5,3,6,4]), 5); - assert_eq!(Solution::max_profit(vec![7,6,4,3,1]), 0); + assert_eq!(Solution::max_profit(vec![7, 1, 5, 3, 6, 4]), 5); + assert_eq!(Solution::max_profit(vec![7, 6, 4, 3, 1]), 0); } } diff --git a/src/n0122_best_time_to_buy_and_sell_stock_ii.rs b/src/n0122_best_time_to_buy_and_sell_stock_ii.rs index 828de554..7b376e6b 100644 --- a/src/n0122_best_time_to_buy_and_sell_stock_ii.rs +++ b/src/n0122_best_time_to_buy_and_sell_stock_ii.rs @@ -2,37 +2,37 @@ * [122] Best Time to Buy and Sell Stock II * * Say you have an array for which the i^th element is the price of a given stock on day i. - * + * * Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). - * + * * Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). - * + * * Example 1: - * - * + * + * * Input: [7,1,5,3,6,4] * Output: 7 * Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. * Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. - * - * + * + * * Example 2: - * - * + * + * * Input: [1,2,3,4,5] * Output: 4 * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. * Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are * engaging multiple transactions at the same time. You must sell before buying again. - * - * + * + * * Example 3: - * - * + * + * * Input: [7,6,4,3,1] * Output: 0 * Explanation: In this case, no transaction is done, i.e. max profit = 0. - * + * */ pub struct Solution {} @@ -42,8 +42,8 @@ impl Solution { pub fn max_profit(prices: Vec) -> i32 { let mut max = 0; for i in 1..prices.len() { - if prices[i] > prices[i-1] { - max += prices[i] - prices[i-1]; + if prices[i] > prices[i - 1] { + max += prices[i] - prices[i - 1]; } } max @@ -58,7 +58,7 @@ mod tests { #[test] fn test_122() { - assert_eq!(Solution::max_profit(vec![7,1,5,3,6,4]), 7); - assert_eq!(Solution::max_profit(vec![1,2,3,4,5]), 4); + assert_eq!(Solution::max_profit(vec![7, 1, 5, 3, 6, 4]), 7); + assert_eq!(Solution::max_profit(vec![1, 2, 3, 4, 5]), 4); } } diff --git a/src/n0123_best_time_to_buy_and_sell_stock_iii.rs b/src/n0123_best_time_to_buy_and_sell_stock_iii.rs index 949060d0..3907c044 100644 --- a/src/n0123_best_time_to_buy_and_sell_stock_iii.rs +++ b/src/n0123_best_time_to_buy_and_sell_stock_iii.rs @@ -2,75 +2,77 @@ * [123] Best Time to Buy and Sell Stock III * * Say you have an array for which the i^th element is the price of a given stock on day i. - * + * * Design an algorithm to find the maximum profit. You may complete at most two transactions. - * + * * Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). - * + * * Example 1: - * - * + * + * * Input: [3,3,5,0,0,3,1,4] * Output: 6 * Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. * Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. - * + * * Example 2: - * - * + * + * * Input: [1,2,3,4,5] * Output: 4 * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. * Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are * engaging multiple transactions at the same time. You must sell before buying again. - * - * + * + * * Example 3: - * - * + * + * * Input: [7,6,4,3,1] * Output: 0 * Explanation: In this case, no transaction is done, i.e. max profit = 0. - * + * */ pub struct Solution {} // submission codes start here /* - 先考虑只进行 1 次交易的情况, 我们求以 i *为售出点*, 只进行 1 次交易获得的最大利润, 那么: +先考虑只进行 1 次交易的情况, 我们求以 i *为售出点*, 只进行 1 次交易获得的最大利润, 那么: - f[i] = if f[i-1] > 0 { f[i-1] } else { 0 } + prices[i] - prices[i-1] +f[i] = if f[i-1] > 0 { f[i-1] } else { 0 } + prices[i] - prices[i-1] - 这很容易解, 解完之后找出 f 里的最大值即可, 但这不容易推广到 K 次交易的情况, 因为这时 f[i] 不代表到 i *为止*的最大利润, 无法作为单独的交易帮助递推 - (到 i 为止的含义是售出点可以在 [0,i] 之间) +这很容易解, 解完之后找出 f 里的最大值即可, 但这不容易推广到 K 次交易的情况, 因为这时 f[i] 不代表到 i *为止*的最大利润, 无法作为单独的交易帮助递推 +(到 i 为止的含义是售出点可以在 [0,i] 之间) - 我们可以稍作改进, 变成求以 i 为结束点, 只进行 1 次交易获得的最大利润, 那么: +我们可以稍作改进, 变成求以 i 为结束点, 只进行 1 次交易获得的最大利润, 那么: - f[i] = max( - f[i-1], - prices[i] - min(prices[j] { j in [0, i-1] }) - ) +f[i] = max( + f[i-1], + prices[i] - min(prices[j] { j in [0, i-1] }) +) - 这仍然是一个 O(N) 的解法, 因为 min(prices[j] { j in [0, i-1] }) 不需要遍历, 可以在递推过程中直接维护好 +这仍然是一个 O(N) 的解法, 因为 min(prices[j] { j in [0, i-1] }) 不需要遍历, 可以在递推过程中直接维护好 - 现在再推广到进行 K 次交易的情况, 那我们要求以 i 为结束点, 进行 k 次交易获得的最大利润, 这时有了变化, 我们可以在 j 之前再进行 K - 1 次交易: +现在再推广到进行 K 次交易的情况, 那我们要求以 i 为结束点, 进行 k 次交易获得的最大利润, 这时有了变化, 我们可以在 j 之前再进行 K - 1 次交易: - f[k, i] = max( - f[k, i-1], - prices[i] + max(f[k-1, j] - prices[j]) { j in [0, i-1] } ) - ) +f[k, i] = max( + f[k, i-1], + prices[i] + max(f[k-1, j] - prices[j]) { j in [0, i-1] } ) +) - 显然, f[0, i] = 0, f[k, 0] = 0 +显然, f[0, i] = 0, f[k, 0] = 0 - 这个算法可以形象地描述一下, 在 k = 1 时, 我们每次要找的就是 i 之前的最低谷点作为这次交易的开始点 j, 而当 k > 1 时, - 我们 i 之前就有可能已经进行过交易了, 这时我们在找开始点 j 时, 就要同时考虑 "直到 j 为止, k-1 次交易的最大收益" - "j 本身的值". 以此来找到一个最佳点 j +这个算法可以形象地描述一下, 在 k = 1 时, 我们每次要找的就是 i 之前的最低谷点作为这次交易的开始点 j, 而当 k > 1 时, +我们 i 之前就有可能已经进行过交易了, 这时我们在找开始点 j 时, 就要同时考虑 "直到 j 为止, k-1 次交易的最大收益" - "j 本身的值". 以此来找到一个最佳点 j - 在实现时, 假如用 Bottom-Up 递推, 那么只需要维护一个 vec[i], 因为每轮递推时只会考虑上一轮的数据, 我们可以复用这个 O(N) 的额外存储空间 - */ +在实现时, 假如用 Bottom-Up 递推, 那么只需要维护一个 vec[i], 因为每轮递推时只会考虑上一轮的数据, 我们可以复用这个 O(N) 的额外存储空间 +*/ impl Solution { pub fn max_profit(prices: Vec) -> i32 { - if prices.is_empty() { return 0 } + if prices.is_empty() { + return 0; + } let max_trans = 2; let mut cache = vec![0; prices.len()]; for trans in 0..max_trans { @@ -79,12 +81,12 @@ impl Solution { for i in 1..prices.len() { // 复用 vec 前暂存一下前一次的计算结果 let temp = cache[i]; - cache[i] = i32::max(cache[i-1], best_buy_in + prices[i]); + cache[i] = i32::max(cache[i - 1], best_buy_in + prices[i]); // 更新 best_buy_in best_buy_in = i32::max(best_buy_in, temp - prices[i]); } } - return *cache.last().unwrap() + return *cache.last().unwrap(); } } @@ -96,6 +98,6 @@ mod tests { #[test] fn test_123() { - assert_eq!(Solution::max_profit(vec![3,3,5,0,0,3,1,4]), 6); + assert_eq!(Solution::max_profit(vec![3, 3, 5, 0, 0, 3, 1, 4]), 6); } } diff --git a/src/n0124_binary_tree_maximum_path_sum.rs b/src/n0124_binary_tree_maximum_path_sum.rs index 7382e11e..5517d18f 100644 --- a/src/n0124_binary_tree_maximum_path_sum.rs +++ b/src/n0124_binary_tree_maximum_path_sum.rs @@ -2,57 +2,57 @@ * [124] Binary Tree Maximum Path Sum * * Given a non-empty binary tree, find the maximum path sum. - * + * * For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. - * + * * Example 1: - * - * + * + * * Input: [1,2,3] - * + * * 1 * / \ * 2 3 - * + * * Output: 6 - * - * + * + * * Example 2: - * - * + * + * * Input: [-10,9,20,null,null,15,7] - * + * * -10 * / \ * 9 20 * / \ * 15 7 - * + * * Output: 42 - * - * + * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here /* - 典型的动态规划, 我们求以 node_i 为 root 的最大和, 可以下推到求 root 的左右子树, 这里要注意, 路径是不能分叉的, 因此 - 我们记 f[node] 为以 node 为根的最大和, 记 g[node] 为 node 为根, *最多连通一侧子树*的最大和 +典型的动态规划, 我们求以 node_i 为 root 的最大和, 可以下推到求 root 的左右子树, 这里要注意, 路径是不能分叉的, 因此 +我们记 f[node] 为以 node 为根的最大和, 记 g[node] 为 node 为根, *最多连通一侧子树*的最大和 - 我们在递推时要用 g[node], f[node] 在递推过程中每次计算一下用于更新 max 即可 +我们在递推时要用 g[node], f[node] 在递推过程中每次计算一下用于更新 max 即可 - g[node_i] = node_i.val + max(g[node_i.left], g[node_i.right], 0) - f[node_i] = node_i.val + max(g[node_i.left], 0) + max(g[node_i.right], 0) +g[node_i] = node_i.val + max(g[node_i.left], g[node_i.right], 0) +f[node_i] = node_i.val + max(g[node_i.left], 0) + max(g[node_i.right], 0) - 显然, g[None] = 0 (None 即空子树), 最终计算到 g[root] 中止, f 的最大值会在计算过程中出现(注意 f[root] 不一定是最大值) +显然, g[None] = 0 (None 即空子树), 最终计算到 g[root] 中止, f 的最大值会在计算过程中出现(注意 f[root] 不一定是最大值) - 每个 node 最大和只依赖与其左右子树的最大和, 因此 Top-down 需要 O(N) 的空间 - Bottom-up 只需要 O(1) 空间 (做后序遍历从叶节点向上递推即可) - */ -use std::rc::Rc; +每个 node 最大和只依赖与其左右子树的最大和, 因此 Top-down 需要 O(N) 的空间 +Bottom-up 只需要 O(1) 空间 (做后序遍历从叶节点向上递推即可) +*/ use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn max_path_sum(root: Option>>) -> i32 { let mut max = i32::min_value(); @@ -64,7 +64,10 @@ impl Solution { if let Some(node) = root { let left = Solution::postorder(node.borrow().left.as_ref(), max); let right = Solution::postorder(node.borrow().right.as_ref(), max); - *max = i32::max(node.borrow().val + i32::max(left, 0) + i32::max(right, 0), *max); + *max = i32::max( + node.borrow().val + i32::max(left, 0) + i32::max(right, 0), + *max, + ); node.borrow().val + i32::max(i32::max(left, right), 0) } else { 0 @@ -80,9 +83,15 @@ mod tests { #[test] fn test_124() { - assert_eq!(Solution::max_path_sum(tree![1,2,3]), 6); - assert_eq!(Solution::max_path_sum(tree![-10,9,20,null,null,15,7]), 42); - assert_eq!(Solution::max_path_sum(tree![5,4,8,11,null,13,4,7,2,null,null,null,1]), 48); + assert_eq!(Solution::max_path_sum(tree![1, 2, 3]), 6); + assert_eq!( + Solution::max_path_sum(tree![-10, 9, 20, null, null, 15, 7]), + 42 + ); + assert_eq!( + Solution::max_path_sum(tree![5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1]), + 48 + ); assert_eq!(Solution::max_path_sum(tree![-3]), -3); } } diff --git a/src/n0125_valid_palindrome.rs b/src/n0125_valid_palindrome.rs index 146b6f3f..b325ac0c 100644 --- a/src/n0125_valid_palindrome.rs +++ b/src/n0125_valid_palindrome.rs @@ -2,23 +2,23 @@ * [125] Valid Palindrome * * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. - * + * * Note: For the purpose of this problem, we define empty string as valid palindrome. - * + * * Example 1: - * - * + * + * * Input: "A man, a plan, a canal: Panama" * Output: true - * - * + * + * * Example 2: - * - * + * + * * Input: "race a car" * Output: false - * - * + * + * */ pub struct Solution {} @@ -26,17 +26,26 @@ pub struct Solution {} impl Solution { pub fn is_palindrome(s: String) -> bool { - if s.is_empty() { return true } + if s.is_empty() { + return true; + } let seq = s.chars().collect::>(); let (mut i, mut j) = (0_usize, seq.len() - 1); while i < j { - while i < seq.len() && !seq[i].is_ascii_alphanumeric(){ i += 1; } - while j > 0 && !seq[j].is_ascii_alphanumeric() { j -= 1; } - if i >= j { break } + while i < seq.len() && !seq[i].is_ascii_alphanumeric() { + i += 1; + } + while j > 0 && !seq[j].is_ascii_alphanumeric() { + j -= 1; + } + if i >= j { + break; + } if seq[i].to_ascii_lowercase() != seq[j].to_ascii_lowercase() { - return false + return false; } - i += 1; j -= 1; + i += 1; + j -= 1; } true } @@ -50,7 +59,10 @@ mod tests { #[test] fn test_125() { - assert_eq!(Solution::is_palindrome("A man, a plan, a canal: Panama".to_owned()), true); + assert_eq!( + Solution::is_palindrome("A man, a plan, a canal: Panama".to_owned()), + true + ); assert_eq!(Solution::is_palindrome("race a car".to_owned()), false); assert_eq!(Solution::is_palindrome("0P".to_owned()), false); } diff --git a/src/n0126_word_ladder_ii.rs b/src/n0126_word_ladder_ii.rs index e1de6fec..b9de6f4c 100644 --- a/src/n0126_word_ladder_ii.rs +++ b/src/n0126_word_ladder_ii.rs @@ -2,76 +2,82 @@ * [126] Word Ladder II * * Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: - * + * *
    * Only one letter can be changed at a time * Each transformed word must exist in the word list. Note that beginWord is not a transformed word. *
- * + * * Note: - * - * + * + * * Return an empty list if there is no such transformation sequence. * All words have the same length. * All words contain only lowercase alphabetic characters. * You may assume no duplicates in the word list. * You may assume beginWord and endWord are non-empty and are not the same. - * - * + * + * * Example 1: - * - * + * + * * Input: * beginWord = "hit", * endWord = "cog", * wordList = ["hot","dot","dog","lot","log","cog"] - * + * * Output: * [ * ["hit","hot","dot","dog","cog"], * ["hit","hot","lot","log","cog"] * ] - * - * + * + * * Example 2: - * - * + * + * * Input: * beginWord = "hit" * endWord = "cog" * wordList = ["hot","dot","dog","lot","log"] - * + * * Output: [] - * + * * Explanation: The endWord "cog" is not in wordList, therefore no possible transformation. - * - * - * - * - * + * + * + * + * + * */ pub struct Solution {} // submission codes start here /* - 假如 A 经过一个字符的变换能得到 B, 则认为 A 与 B 之间有通路, 转化为一个 BFS 找无权图最短路径的问题 +假如 A 经过一个字符的变换能得到 B, 则认为 A 与 B 之间有通路, 转化为一个 BFS 找无权图最短路径的问题 - 实现时, 可以先把图构造出来, 复杂度 O(L*N^2) (L 是字符串长度), 也可以每次都回到数组里去找连通点, 时间复杂度不变 +实现时, 可以先把图构造出来, 复杂度 O(L*N^2) (L 是字符串长度), 也可以每次都回到数组里去找连通点, 时间复杂度不变 - 由于要记录所有的路径, 因此我们需要把每个点的可能前置节点都记录下来, 最后用一个 DFS 或 BFS 找出所有路径 +由于要记录所有的路径, 因此我们需要把每个点的可能前置节点都记录下来, 最后用一个 DFS 或 BFS 找出所有路径 - 暂时想不到更好的办法 - */ +暂时想不到更好的办法 +*/ -use std::collections::VecDeque; use std::collections::HashSet; +use std::collections::VecDeque; impl Solution { - pub fn find_ladders(begin_word: String, end_word: String, word_list: Vec) -> Vec> { + pub fn find_ladders( + begin_word: String, + end_word: String, + word_list: Vec, + ) -> Vec> { let mut res = Vec::new(); let len = word_list.len(); let target = word_list.iter().position(|s| s == &end_word); - if target.is_none() { return res } + if target.is_none() { + return res; + } let target = target.unwrap(); let mut deq = VecDeque::new(); deq.push_back(target); @@ -84,15 +90,21 @@ impl Solution { while let Some(i) = deq.pop_front() { if Solution::connect(&begin_word, &word_list[i]) { // complete the path using dfs - if paths[i].0 > shortest { continue } + if paths[i].0 > shortest { + continue; + } Solution::dfs(i, vec![begin_word.clone()], &word_list, &paths, &mut res); shortest = paths[i].0; find_shortest = true; } // we have found the shortest path, just drain all the nodes in deq - if find_shortest { continue } + if find_shortest { + continue; + } for j in 0..len { - if j == i { continue } + if j == i { + continue; + } if Solution::connect(&word_list[i], &word_list[j]) { if paths[i].0 + 1 <= paths[j].0 { let mut prev = &mut paths[j].1; @@ -109,11 +121,17 @@ impl Solution { res } - fn dfs(curr: usize, mut path: Vec, words: &Vec, paths: &Vec<(i32, Vec)>, res: &mut Vec>) { + fn dfs( + curr: usize, + mut path: Vec, + words: &Vec, + paths: &Vec<(i32, Vec)>, + res: &mut Vec>, + ) { path.push(words[curr].clone()); if paths[curr].1.is_empty() { res.push(path); - return + return; } for &prev in paths[curr].1.iter() { Solution::dfs(prev, path.clone(), words, paths, res); @@ -122,14 +140,18 @@ impl Solution { #[inline(always)] fn connect(s1: &str, s2: &str) -> bool { - if s1.len() != s2.len() { return false } + if s1.len() != s2.len() { + return false; + } let mut iter1 = s1.chars().into_iter(); let mut iter2 = s2.chars().into_iter(); let mut diff = 0; while let (Some(c1), Some(c2)) = (iter1.next(), iter2.next()) { if c1 != c2 { diff += 1; - if diff >= 2 { return false } + if diff >= 2 { + return false; + } } } true @@ -145,20 +167,88 @@ mod tests { #[test] fn test_126() { assert_eq!( - Solution::find_ladders("hit".to_owned(), "cog".to_owned(), - vec_string!["hot","dot","dog","lot","log","cog"]), + Solution::find_ladders( + "hit".to_owned(), + "cog".to_owned(), + vec_string!["hot", "dot", "dog", "lot", "log", "cog"] + ), vec![ - vec_string!["hit","hot","dot","dog","cog"], - vec_string!["hit","hot","lot","log","cog"], + vec_string!["hit", "hot", "dot", "dog", "cog"], + vec_string!["hit", "hot", "lot", "log", "cog"], ] ); assert_eq!( - Solution::find_ladders("cet".to_owned(), "ism".to_owned(), - vec_string!["kid","tag","pup","ail","tun","woo","erg","luz","brr","gay","sip","kay","per","val","mes","ohs","now","boa","cet","pal","bar","die","war","hay","eco","pub","lob","rue","fry","lit","rex","jan","cot","bid","ali","pay","col","gum","ger","row","won","dan","rum","fad","tut","sag","yip","sui","ark","has","zip","fez","own","ump","dis","ads","max","jaw","out","btu","ana","gap","cry","led","abe","box","ore","pig","fie","toy","fat","cal","lie","noh","sew","ono","tam","flu","mgm","ply","awe","pry","tit","tie","yet","too","tax","jim","san","pan","map","ski","ova","wed","non","wac","nut","why","bye","lye","oct","old","fin","feb","chi","sap","owl","log","tod","dot","bow","fob","for","joe","ivy","fan","age","fax","hip","jib","mel","hus","sob","ifs","tab","ara","dab","jag","jar","arm","lot","tom","sax","tex","yum","pei","wen","wry","ire","irk","far","mew","wit","doe","gas","rte","ian","pot","ask","wag","hag","amy","nag","ron","soy","gin","don","tug","fay","vic","boo","nam","ave","buy","sop","but","orb","fen","paw","his","sub","bob","yea","oft","inn","rod","yam","pew","web","hod","hun","gyp","wei","wis","rob","gad","pie","mon","dog","bib","rub","ere","dig","era","cat","fox","bee","mod","day","apr","vie","nev","jam","pam","new","aye","ani","and","ibm","yap","can","pyx","tar","kin","fog","hum","pip","cup","dye","lyx","jog","nun","par","wan","fey","bus","oak","bad","ats","set","qom","vat","eat","pus","rev","axe","ion","six","ila","lao","mom","mas","pro","few","opt","poe","art","ash","oar","cap","lop","may","shy","rid","bat","sum","rim","fee","bmw","sky","maj","hue","thy","ava","rap","den","fla","auk","cox","ibo","hey","saw","vim","sec","ltd","you","its","tat","dew","eva","tog","ram","let","see","zit","maw","nix","ate","gig","rep","owe","ind","hog","eve","sam","zoo","any","dow","cod","bed","vet","ham","sis","hex","via","fir","nod","mao","aug","mum","hoe","bah","hal","keg","hew","zed","tow","gog","ass","dem","who","bet","gos","son","ear","spy","kit","boy","due","sen","oaf","mix","hep","fur","ada","bin","nil","mia","ewe","hit","fix","sad","rib","eye","hop","haw","wax","mid","tad","ken","wad","rye","pap","bog","gut","ito","woe","our","ado","sin","mad","ray","hon","roy","dip","hen","iva","lug","asp","hui","yak","bay","poi","yep","bun","try","lad","elm","nat","wyo","gym","dug","toe","dee","wig","sly","rip","geo","cog","pas","zen","odd","nan","lay","pod","fit","hem","joy","bum","rio","yon","dec","leg","put","sue","dim","pet","yaw","nub","bit","bur","sid","sun","oil","red","doc","moe","caw","eel","dix","cub","end","gem","off","yew","hug","pop","tub","sgt","lid","pun","ton","sol","din","yup","jab","pea","bug","gag","mil","jig","hub","low","did","tin","get","gte","sox","lei","mig","fig","lon","use","ban","flo","nov","jut","bag","mir","sty","lap","two","ins","con","ant","net","tux","ode","stu","mug","cad","nap","gun","fop","tot","sow","sal","sic","ted","wot","del","imp","cob","way","ann","tan","mci","job","wet","ism","err","him","all","pad","hah","hie","aim","ike","jed","ego","mac","baa","min","com","ill","was","cab","ago","ina","big","ilk","gal","tap","duh","ola","ran","lab","top","gob","hot","ora","tia","kip","han","met","hut","she","sac","fed","goo","tee","ell","not","act","gil","rut","ala","ape","rig","cid","god","duo","lin","aid","gel","awl","lag","elf","liz","ref","aha","fib","oho","tho","her","nor","ace","adz","fun","ned","coo","win","tao","coy","van","man","pit","guy","foe","hid","mai","sup","jay","hob","mow","jot","are","pol","arc","lax","aft","alb","len","air","pug","pox","vow","got","meg","zoe","amp","ale","bud","gee","pin","dun","pat","ten","mob"]), + Solution::find_ladders( + "cet".to_owned(), + "ism".to_owned(), + vec_string![ + "kid", "tag", "pup", "ail", "tun", "woo", "erg", "luz", "brr", "gay", "sip", + "kay", "per", "val", "mes", "ohs", "now", "boa", "cet", "pal", "bar", "die", + "war", "hay", "eco", "pub", "lob", "rue", "fry", "lit", "rex", "jan", "cot", + "bid", "ali", "pay", "col", "gum", "ger", "row", "won", "dan", "rum", "fad", + "tut", "sag", "yip", "sui", "ark", "has", "zip", "fez", "own", "ump", "dis", + "ads", "max", "jaw", "out", "btu", "ana", "gap", "cry", "led", "abe", "box", + "ore", "pig", "fie", "toy", "fat", "cal", "lie", "noh", "sew", "ono", "tam", + "flu", "mgm", "ply", "awe", "pry", "tit", "tie", "yet", "too", "tax", "jim", + "san", "pan", "map", "ski", "ova", "wed", "non", "wac", "nut", "why", "bye", + "lye", "oct", "old", "fin", "feb", "chi", "sap", "owl", "log", "tod", "dot", + "bow", "fob", "for", "joe", "ivy", "fan", "age", "fax", "hip", "jib", "mel", + "hus", "sob", "ifs", "tab", "ara", "dab", "jag", "jar", "arm", "lot", "tom", + "sax", "tex", "yum", "pei", "wen", "wry", "ire", "irk", "far", "mew", "wit", + "doe", "gas", "rte", "ian", "pot", "ask", "wag", "hag", "amy", "nag", "ron", + "soy", "gin", "don", "tug", "fay", "vic", "boo", "nam", "ave", "buy", "sop", + "but", "orb", "fen", "paw", "his", "sub", "bob", "yea", "oft", "inn", "rod", + "yam", "pew", "web", "hod", "hun", "gyp", "wei", "wis", "rob", "gad", "pie", + "mon", "dog", "bib", "rub", "ere", "dig", "era", "cat", "fox", "bee", "mod", + "day", "apr", "vie", "nev", "jam", "pam", "new", "aye", "ani", "and", "ibm", + "yap", "can", "pyx", "tar", "kin", "fog", "hum", "pip", "cup", "dye", "lyx", + "jog", "nun", "par", "wan", "fey", "bus", "oak", "bad", "ats", "set", "qom", + "vat", "eat", "pus", "rev", "axe", "ion", "six", "ila", "lao", "mom", "mas", + "pro", "few", "opt", "poe", "art", "ash", "oar", "cap", "lop", "may", "shy", + "rid", "bat", "sum", "rim", "fee", "bmw", "sky", "maj", "hue", "thy", "ava", + "rap", "den", "fla", "auk", "cox", "ibo", "hey", "saw", "vim", "sec", "ltd", + "you", "its", "tat", "dew", "eva", "tog", "ram", "let", "see", "zit", "maw", + "nix", "ate", "gig", "rep", "owe", "ind", "hog", "eve", "sam", "zoo", "any", + "dow", "cod", "bed", "vet", "ham", "sis", "hex", "via", "fir", "nod", "mao", + "aug", "mum", "hoe", "bah", "hal", "keg", "hew", "zed", "tow", "gog", "ass", + "dem", "who", "bet", "gos", "son", "ear", "spy", "kit", "boy", "due", "sen", + "oaf", "mix", "hep", "fur", "ada", "bin", "nil", "mia", "ewe", "hit", "fix", + "sad", "rib", "eye", "hop", "haw", "wax", "mid", "tad", "ken", "wad", "rye", + "pap", "bog", "gut", "ito", "woe", "our", "ado", "sin", "mad", "ray", "hon", + "roy", "dip", "hen", "iva", "lug", "asp", "hui", "yak", "bay", "poi", "yep", + "bun", "try", "lad", "elm", "nat", "wyo", "gym", "dug", "toe", "dee", "wig", + "sly", "rip", "geo", "cog", "pas", "zen", "odd", "nan", "lay", "pod", "fit", + "hem", "joy", "bum", "rio", "yon", "dec", "leg", "put", "sue", "dim", "pet", + "yaw", "nub", "bit", "bur", "sid", "sun", "oil", "red", "doc", "moe", "caw", + "eel", "dix", "cub", "end", "gem", "off", "yew", "hug", "pop", "tub", "sgt", + "lid", "pun", "ton", "sol", "din", "yup", "jab", "pea", "bug", "gag", "mil", + "jig", "hub", "low", "did", "tin", "get", "gte", "sox", "lei", "mig", "fig", + "lon", "use", "ban", "flo", "nov", "jut", "bag", "mir", "sty", "lap", "two", + "ins", "con", "ant", "net", "tux", "ode", "stu", "mug", "cad", "nap", "gun", + "fop", "tot", "sow", "sal", "sic", "ted", "wot", "del", "imp", "cob", "way", + "ann", "tan", "mci", "job", "wet", "ism", "err", "him", "all", "pad", "hah", + "hie", "aim", "ike", "jed", "ego", "mac", "baa", "min", "com", "ill", "was", + "cab", "ago", "ina", "big", "ilk", "gal", "tap", "duh", "ola", "ran", "lab", + "top", "gob", "hot", "ora", "tia", "kip", "han", "met", "hut", "she", "sac", + "fed", "goo", "tee", "ell", "not", "act", "gil", "rut", "ala", "ape", "rig", + "cid", "god", "duo", "lin", "aid", "gel", "awl", "lag", "elf", "liz", "ref", + "aha", "fib", "oho", "tho", "her", "nor", "ace", "adz", "fun", "ned", "coo", + "win", "tao", "coy", "van", "man", "pit", "guy", "foe", "hid", "mai", "sup", + "jay", "hob", "mow", "jot", "are", "pol", "arc", "lax", "aft", "alb", "len", + "air", "pug", "pox", "vow", "got", "meg", "zoe", "amp", "ale", "bud", "gee", + "pin", "dun", "pat", "ten", "mob" + ] + ), vec![ - vec_string!["cet","get","gee","gte","ate","ats","its","ito","ibo","ibm","ism"], - vec_string!["cet","cat","can","ian","inn","ins","its","ito","ibo","ibm","ism"], - vec_string!["cet","cot","con","ion","inn","ins","its","ito","ibo","ibm","ism"], + vec_string![ + "cet", "get", "gee", "gte", "ate", "ats", "its", "ito", "ibo", "ibm", "ism" + ], + vec_string![ + "cet", "cat", "can", "ian", "inn", "ins", "its", "ito", "ibo", "ibm", "ism" + ], + vec_string![ + "cet", "cot", "con", "ion", "inn", "ins", "its", "ito", "ibo", "ibm", "ism" + ], ] ); } diff --git a/src/n0127_word_ladder.rs b/src/n0127_word_ladder.rs index 183efe93..6c8fbfa6 100644 --- a/src/n0127_word_ladder.rs +++ b/src/n0127_word_ladder.rs @@ -2,60 +2,62 @@ * [127] Word Ladder * * Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: - * + * *
    * Only one letter can be changed at a time. * Each transformed word must exist in the word list. Note that beginWord is not a transformed word. *
- * + * * Note: - * - * + * + * * Return 0 if there is no such transformation sequence. * All words have the same length. * All words contain only lowercase alphabetic characters. * You may assume no duplicates in the word list. * You may assume beginWord and endWord are non-empty and are not the same. - * - * + * + * * Example 1: - * - * + * + * * Input: * beginWord = "hit", * endWord = "cog", * wordList = ["hot","dot","dog","lot","log","cog"] - * + * * Output: 5 - * + * * Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", * return its length 5. - * - * + * + * * Example 2: - * - * + * + * * Input: * beginWord = "hit" * endWord = "cog" * wordList = ["hot","dot","dog","lot","log"] - * + * * Output: 0 - * + * * Explanation: The endWord "cog" is not in wordList, therefore no possible transformation. - * + * */ pub struct Solution {} // submission codes start here -use std::collections::VecDeque; use std::collections::HashSet; +use std::collections::VecDeque; impl Solution { pub fn ladder_length(begin_word: String, end_word: String, word_list: Vec) -> i32 { let len = word_list.len(); let target = word_list.iter().position(|s| s == &end_word); - if target.is_none() { return 0 } + if target.is_none() { + return 0; + } let target = target.unwrap(); let mut deq = VecDeque::new(); let mut distance = vec![0; len]; @@ -81,14 +83,18 @@ impl Solution { #[inline(always)] fn connect(s1: &str, s2: &str) -> bool { - if s1.len() != s2.len() { return false } + if s1.len() != s2.len() { + return false; + } let mut iter1 = s1.chars().into_iter(); let mut iter2 = s2.chars().into_iter(); let mut diff = 0; while let (Some(c1), Some(c2)) = (iter1.next(), iter2.next()) { if c1 != c2 { diff += 1; - if diff >= 2 { return false } + if diff >= 2 { + return false; + } } } true @@ -104,13 +110,19 @@ mod tests { #[test] fn test_127() { assert_eq!( - Solution::ladder_length("hit".to_owned(), "cog".to_owned(), - vec_string!["hot","dot","dog","lot","log","cog"]), + Solution::ladder_length( + "hit".to_owned(), + "cog".to_owned(), + vec_string!["hot", "dot", "dog", "lot", "log", "cog"] + ), 5 ); assert_eq!( - Solution::ladder_length("hit".to_owned(), "cog".to_owned(), - vec_string!["hot","dot","dog","lot","log"]), + Solution::ladder_length( + "hit".to_owned(), + "cog".to_owned(), + vec_string!["hot", "dot", "dog", "lot", "log"] + ), 0 ); } diff --git a/src/n0128_longest_consecutive_sequence.rs b/src/n0128_longest_consecutive_sequence.rs index 737c4568..ef77362b 100644 --- a/src/n0128_longest_consecutive_sequence.rs +++ b/src/n0128_longest_consecutive_sequence.rs @@ -2,44 +2,45 @@ * [128] Longest Consecutive Sequence * * Given an unsorted array of integers, find the length of the longest consecutive elements sequence. - * + * * Your algorithm should run in O(n) complexity. - * + * * Example: - * - * + * + * * Input: [100, 4, 200, 1, 3, 2] * Output: 4 * Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. - * - * + * + * */ pub struct Solution {} // submission codes start here /* - 要找到连续子串, 基本策略就是对每个 num, 判断 num+1, num+2, num+3... 是否在数组中, 直到不再连续 +要找到连续子串, 基本策略就是对每个 num, 判断 num+1, num+2, num+3... 是否在数组中, 直到不再连续 - 工程里写的话用排序是最清晰可维护的(需求变了很好改), 排序之后查找 num+1 是否存在就只需要 O(1) 的复杂度了: - 看下一个元素是不是 num+1 即可 +工程里写的话用排序是最清晰可维护的(需求变了很好改), 排序之后查找 num+1 是否存在就只需要 O(1) 的复杂度了: +看下一个元素是不是 num+1 即可 - 但题目一定要求 O(N) 的解法, 只能想些奇怪的办法了, HashSet 也能达到 O(1) 的查找效率. 但假如对每个元素 - 都做一遍, 最差就是 O(N^2) 了, 可以发现对于一个连续序列 1,2,3,4,5,6 我们从 1 开始查就能找到这个序列, - 从 2,3,4,5,6 开始查都是在做重复计算, 因此对于一个 num, 假如 num-1 存在于 HashSet 中, 我们就不需要考虑 - 它了, 因为它是一次重复的计算. - */ +但题目一定要求 O(N) 的解法, 只能想些奇怪的办法了, HashSet 也能达到 O(1) 的查找效率. 但假如对每个元素 +都做一遍, 最差就是 O(N^2) 了, 可以发现对于一个连续序列 1,2,3,4,5,6 我们从 1 开始查就能找到这个序列, +从 2,3,4,5,6 开始查都是在做重复计算, 因此对于一个 num, 假如 num-1 存在于 HashSet 中, 我们就不需要考虑 +它了, 因为它是一次重复的计算. +*/ use std::collections::HashSet; impl Solution { pub fn longest_consecutive(nums: Vec) -> i32 { let mut max = 0; let nums = nums.into_iter().collect::>(); for &num in nums.iter() { - if !nums.contains(&(num-1)) { + if !nums.contains(&(num - 1)) { let mut curr = num; let mut curr_max = 1; - while nums.contains(&(curr+1)) { - curr += 1; curr_max += 1; + while nums.contains(&(curr + 1)) { + curr += 1; + curr_max += 1; } max = i32::max(curr_max, max); } @@ -56,6 +57,6 @@ mod tests { #[test] fn test_128() { - assert_eq!(Solution::longest_consecutive(vec![100,4,200,1,3,2]), 4) + assert_eq!(Solution::longest_consecutive(vec![100, 4, 200, 1, 3, 2]), 4) } } diff --git a/src/n0129_sum_root_to_leaf_numbers.rs b/src/n0129_sum_root_to_leaf_numbers.rs index b29dc36b..5e423c34 100644 --- a/src/n0129_sum_root_to_leaf_numbers.rs +++ b/src/n0129_sum_root_to_leaf_numbers.rs @@ -2,16 +2,16 @@ * [129] Sum Root to Leaf Numbers * * Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. - * + * * An example is the root-to-leaf path 1->2->3 which represents the number 123. - * + * * Find the total sum of all root-to-leaf numbers. - * + * * Note: A leaf is a node with no children. - * + * * Example: - * - * + * + * * Input: [1,2,3] * 1 * / \ @@ -21,10 +21,10 @@ * The root-to-leaf path 1->2 represents the number 12. * The root-to-leaf path 1->3 represents the number 13. * Therefore, sum = 12 + 13 = 25. - * + * * Example 2: - * - * + * + * * Input: [4,9,0,5,1] * 4 * / \ @@ -37,24 +37,26 @@ * The root-to-leaf path 4->9->1 represents the number 491. * The root-to-leaf path 4->0 represents the number 40. * Therefore, sum = 495 + 491 + 40 = 1026. - * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; use std::collections::VecDeque; +use std::rc::Rc; impl Solution { pub fn sum_numbers(root: Option>>) -> i32 { let mut sum = 0; - if root.is_none() { return sum } + if root.is_none() { + return sum; + } let mut deq = VecDeque::new(); deq.push_back((root.clone(), 0)); while let Some(item) = deq.pop_front() { - if let (Some(node), acc) = item { + if let (Some(node), acc) = item { let acc = acc * 10 + node.borrow().val; if node.borrow().left.is_none() && node.borrow().right.is_none() { sum += acc; @@ -76,7 +78,7 @@ mod tests { #[test] fn test_129() { - assert_eq!(Solution::sum_numbers(tree![1,2,3]), 25); - assert_eq!(Solution::sum_numbers(tree![4,9,0,5,1]), 1026); + assert_eq!(Solution::sum_numbers(tree![1, 2, 3]), 25); + assert_eq!(Solution::sum_numbers(tree![4, 9, 0, 5, 1]), 1026); } } diff --git a/src/n0130_surrounded_regions.rs b/src/n0130_surrounded_regions.rs index e4718d0a..90135ae8 100644 --- a/src/n0130_surrounded_regions.rs +++ b/src/n0130_surrounded_regions.rs @@ -2,54 +2,56 @@ * [130] Surrounded Regions * * Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. - * + * * A region is captured by flipping all 'O's into 'X's in that surrounded region. - * + * * Example: - * - * + * + * * X X X X * X O O X * X X O X * X O X X - * - * + * + * * After running your function, the board should be: - * - * + * + * * X X X X * X X X X * X X X X * X O X X - * - * + * + * * Explanation: - * + * * Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically. - * + * */ pub struct Solution {} // submission codes start here /* - 从最外层开始, 基于为 'O' 的格子做 DFS, 将与边界连接的所有 'O' 标记为一个特殊 char, 最后将没有标记到的 'O' 全部标记为 'X' - */ +从最外层开始, 基于为 'O' 的格子做 DFS, 将与边界连接的所有 'O' 标记为一个特殊 char, 最后将没有标记到的 'O' 全部标记为 'X' +*/ impl Solution { pub fn solve(board: &mut Vec>) { - if board.is_empty() || board[0].is_empty() { return } + if board.is_empty() || board[0].is_empty() { + return; + } let (height, width) = (board.len(), board[0].len()); // 遍历最外层的 4 条边 for j in 0..width { Solution::dfs(0, j, height, width, board); - Solution::dfs(height-1, j, height, width, board); + Solution::dfs(height - 1, j, height, width, board); } - for i in 1..height-1 { + for i in 1..height - 1 { Solution::dfs(i, 0, height, width, board); - Solution::dfs(i, width-1, height, width, board); + Solution::dfs(i, width - 1, height, width, board); } - for k in 0..height*width { - board[k/width][k%width] = if board[k/width][k%width] == '_' { + for k in 0..height * width { + board[k / width][k % width] = if board[k / width][k % width] == '_' { 'O' } else { 'X' @@ -60,10 +62,18 @@ impl Solution { fn dfs(i: usize, j: usize, height: usize, width: usize, board: &mut Vec>) { if board[i][j] == 'O' { board[i][j] = '_'; - if i > 1 { Solution::dfs(i-1, j, height, width, board) } - if j > 1 { Solution::dfs(i, j-1, height, width, board) } - if i + 1 < height { Solution::dfs(i+1, j, height, width, board) } - if j + 1 < width { Solution::dfs(i, j+1, height, width, board) } + if i > 1 { + Solution::dfs(i - 1, j, height, width, board) + } + if j > 1 { + Solution::dfs(i, j - 1, height, width, board) + } + if i + 1 < height { + Solution::dfs(i + 1, j, height, width, board) + } + if j + 1 < width { + Solution::dfs(i, j + 1, height, width, board) + } } } } @@ -77,94 +87,132 @@ mod tests { #[test] fn test_130() { let mut matrix = vec![ - vec!['X','X','X','X'], - vec!['X','O','O','X'], - vec!['X','X','O','X'], - vec!['X','O','X','X'], + vec!['X', 'X', 'X', 'X'], + vec!['X', 'O', 'O', 'X'], + vec!['X', 'X', 'O', 'X'], + vec!['X', 'O', 'X', 'X'], ]; Solution::solve(&mut matrix); assert_eq!( matrix, vec![ - vec!['X','X','X','X'], - vec!['X','X','X','X'], - vec!['X','X','X','X'], - vec!['X','O','X','X'], + vec!['X', 'X', 'X', 'X'], + vec!['X', 'X', 'X', 'X'], + vec!['X', 'X', 'X', 'X'], + vec!['X', 'O', 'X', 'X'], ] ); let mut matrix = vec![ - vec!['X','X','X','X'], - vec!['X','O','O','X'], - vec!['X','O','O','X'], - vec!['X','X','X','X'], + vec!['X', 'X', 'X', 'X'], + vec!['X', 'O', 'O', 'X'], + vec!['X', 'O', 'O', 'X'], + vec!['X', 'X', 'X', 'X'], ]; Solution::solve(&mut matrix); assert_eq!( matrix, vec![ - vec!['X','X','X','X'], - vec!['X','X','X','X'], - vec!['X','X','X','X'], - vec!['X','X','X','X'], + vec!['X', 'X', 'X', 'X'], + vec!['X', 'X', 'X', 'X'], + vec!['X', 'X', 'X', 'X'], + vec!['X', 'X', 'X', 'X'], ] ); let mut matrix = vec![ - vec!['X','X','X','X'], - vec!['O','X','O','X'], - vec!['O','X','O','X'], - vec!['X','O','X','X'], + vec!['X', 'X', 'X', 'X'], + vec!['O', 'X', 'O', 'X'], + vec!['O', 'X', 'O', 'X'], + vec!['X', 'O', 'X', 'X'], ]; Solution::solve(&mut matrix); assert_eq!( matrix, vec![ - vec!['X','X','X','X'], - vec!['O','X','X','X'], - vec!['O','X','X','X'], - vec!['X','O','X','X'], + vec!['X', 'X', 'X', 'X'], + vec!['O', 'X', 'X', 'X'], + vec!['O', 'X', 'X', 'X'], + vec!['X', 'O', 'X', 'X'], ] ); let mut matrix = vec![ - vec!['X','X','X','X','O','X'], - vec!['O','X','X','O','O','X'], - vec!['X','O','X','O','O','O'], - vec!['X','O','O','O','X','O'], - vec!['O','O','X','X','O','X'], - vec!['X','O','X','O','X','X'], + vec!['X', 'X', 'X', 'X', 'O', 'X'], + vec!['O', 'X', 'X', 'O', 'O', 'X'], + vec!['X', 'O', 'X', 'O', 'O', 'O'], + vec!['X', 'O', 'O', 'O', 'X', 'O'], + vec!['O', 'O', 'X', 'X', 'O', 'X'], + vec!['X', 'O', 'X', 'O', 'X', 'X'], ]; Solution::solve(&mut matrix); assert_eq!( matrix, vec![ - vec!['X','X','X','X','O','X'], - vec!['O','X','X','O','O','X'], - vec!['X','O','X','O','O','O'], - vec!['X','O','O','O','X','O'], - vec!['O','O','X','X','X','X'], - vec!['X','O','X','O','X','X'], + vec!['X', 'X', 'X', 'X', 'O', 'X'], + vec!['O', 'X', 'X', 'O', 'O', 'X'], + vec!['X', 'O', 'X', 'O', 'O', 'O'], + vec!['X', 'O', 'O', 'O', 'X', 'O'], + vec!['O', 'O', 'X', 'X', 'X', 'X'], + vec!['X', 'O', 'X', 'O', 'X', 'X'], ] ); let mut matrix = vec![ - vec!['X','X','X','X','X','X','X','X','X','X','X','X','X','X','X','X','X','X','X','X'], - vec!['X','X','X','X','X','X','X','X','X','O','O','O','X','X','X','X','X','X','X','X'], - vec!['X','X','X','X','X','O','O','O','X','O','X','O','X','X','X','X','X','X','X','X'], - vec!['X','X','X','X','X','O','X','O','X','O','X','O','O','O','X','X','X','X','X','X'], - vec!['X','X','X','X','X','O','X','O','O','O','X','X','X','X','X','X','X','X','X','X'], - vec!['X','X','X','X','X','O','X','X','X','X','X','X','X','X','X','X','X','X','X','X']]; + vec![ + 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', + 'X', 'X', 'X', 'X', + ], + vec![ + 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'O', 'O', 'O', 'X', 'X', 'X', 'X', + 'X', 'X', 'X', 'X', + ], + vec![ + 'X', 'X', 'X', 'X', 'X', 'O', 'O', 'O', 'X', 'O', 'X', 'O', 'X', 'X', 'X', 'X', + 'X', 'X', 'X', 'X', + ], + vec![ + 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'O', 'X', 'O', 'X', 'O', 'O', 'O', 'X', 'X', + 'X', 'X', 'X', 'X', + ], + vec![ + 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'O', 'O', 'O', 'X', 'X', 'X', 'X', 'X', 'X', + 'X', 'X', 'X', 'X', + ], + vec![ + 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', + 'X', 'X', 'X', 'X', + ], + ]; Solution::solve(&mut matrix); assert_eq!( matrix, vec![ - vec!['X','X','X','X','X','X','X','X','X','X','X','X','X','X','X','X','X','X','X','X'], - vec!['X','X','X','X','X','X','X','X','X','O','O','O','X','X','X','X','X','X','X','X'], - vec!['X','X','X','X','X','O','O','O','X','O','X','O','X','X','X','X','X','X','X','X'], - vec!['X','X','X','X','X','O','X','O','X','O','X','O','O','O','X','X','X','X','X','X'], - vec!['X','X','X','X','X','O','X','O','O','O','X','X','X','X','X','X','X','X','X','X'], - vec!['X','X','X','X','X','O','X','X','X','X','X','X','X','X','X','X','X','X','X','X']] + vec![ + 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', + 'X', 'X', 'X', 'X' + ], + vec![ + 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'O', 'O', 'O', 'X', 'X', 'X', 'X', + 'X', 'X', 'X', 'X' + ], + vec![ + 'X', 'X', 'X', 'X', 'X', 'O', 'O', 'O', 'X', 'O', 'X', 'O', 'X', 'X', 'X', 'X', + 'X', 'X', 'X', 'X' + ], + vec![ + 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'O', 'X', 'O', 'X', 'O', 'O', 'O', 'X', 'X', + 'X', 'X', 'X', 'X' + ], + vec![ + 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'O', 'O', 'O', 'X', 'X', 'X', 'X', 'X', 'X', + 'X', 'X', 'X', 'X' + ], + vec![ + 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', + 'X', 'X', 'X', 'X' + ] + ] ); } } diff --git a/src/n0131_palindrome_partitioning.rs b/src/n0131_palindrome_partitioning.rs index 3c976271..a9f52608 100644 --- a/src/n0131_palindrome_partitioning.rs +++ b/src/n0131_palindrome_partitioning.rs @@ -2,77 +2,90 @@ * [131] Palindrome Partitioning * * Given a string s, partition s such that every substring of the partition is a palindrome. - * + * * Return all possible palindrome partitioning of s. - * + * * Example: - * - * + * + * * Input: "aab" * Output: * [ * ["aa","b"], * ["a","a","b"] * ] - * - * + * + * */ pub struct Solution {} // submission codes start here /* - 记 n 个字符的回文拆分方式是 f(n) 种, 则: +记 n 个字符的回文拆分方式是 f(n) 种, 则: - f(n) = (0..n).iter().fold(0, |acc, i| { - if is_palindrome(s[i..n]) { acc + f(i-1) } else { acc } - }) +f(n) = (0..n).iter().fold(0, |acc, i| { + if is_palindrome(s[i..n]) { acc + f(i-1) } else { acc } +}) - 按这种方式向上递推即可, 时间复杂度为 O(N^3), 空间复杂度 O(N), 显然, is_palindrome 这一步仍然有重复计算 +按这种方式向上递推即可, 时间复杂度为 O(N^3), 空间复杂度 O(N), 显然, is_palindrome 这一步仍然有重复计算 - is_palindrome(s[i..n]) = s[i] == s[n] && is_palindrome(s[i+1..n-1]) +is_palindrome(s[i..n]) = s[i] == s[n] && is_palindrome(s[i+1..n-1]) - 存储所有 i, n 的 is_palindrome 结果, 则可以优化 is_palindrome 的时间到 O(1) +存储所有 i, n 的 is_palindrome 结果, 则可以优化 is_palindrome 的时间到 O(1) - 最后的复杂度: 时间 O(N^2), 空间 O(N^2) - */ +最后的复杂度: 时间 O(N^2), 空间 O(N^2) +*/ impl Solution { pub fn partition(s: String) -> Vec> { let s = s.chars().collect::>(); - if s.is_empty() { return Vec::new() } + if s.is_empty() { + return Vec::new(); + } let mut palindrome_cache = vec![vec![None; s.len()]; s.len()]; let mut res: Vec>> = Vec::with_capacity(s.len()); - res.push(vec![vec![(0,1)]]); + res.push(vec![vec![(0, 1)]]); for n in 1..s.len() { let mut curr: Vec> = Vec::new(); - for i in 0..n+1 { + for i in 0..n + 1 { if Solution::is_palindrome(&mut palindrome_cache, &s, i, n) { if i > 0 { - for vec in res[i-1].iter() { + for vec in res[i - 1].iter() { let mut new_vec = vec.clone(); - new_vec.push((i,n+1)); + new_vec.push((i, n + 1)); curr.push(new_vec); } } else { - curr.push(vec![(i, n+1)]); + curr.push(vec![(i, n + 1)]); } } } res.push(curr); } - (*res[s.len()-1]).into_iter().map(|vec| { - vec.iter() - .map(|&range| {s[range.0..range.1].iter().collect::()}) - .collect::>() - }).collect() + (*res[s.len() - 1]) + .into_iter() + .map(|vec| { + vec.iter() + .map(|&range| s[range.0..range.1].iter().collect::()) + .collect::>() + }) + .collect() } - fn is_palindrome(cache: &mut Vec>>, s: &Vec, i: usize, j: usize) -> bool { - if j <= i { return true } + fn is_palindrome( + cache: &mut Vec>>, + s: &Vec, + i: usize, + j: usize, + ) -> bool { + if j <= i { + return true; + } if let Some(result) = cache[i][j] { result } else { - let result = s[i] == s[j] && (i + 1 > s.len() || j < 1 || Solution::is_palindrome(cache, s, i+1, j-1)); + let result = s[i] == s[j] + && (i + 1 > s.len() || j < 1 || Solution::is_palindrome(cache, s, i + 1, j - 1)); cache[i][j] = Some(result); result } @@ -89,10 +102,8 @@ mod tests { fn test_131() { assert_eq!( Solution::partition("aab".to_owned()), - vec![ - vec_string!["aa", "b"], - vec_string!["a", "a", "b"], - ]); + vec![vec_string!["aa", "b"], vec_string!["a", "a", "b"],] + ); assert_eq!( Solution::partition("aaa".to_owned()), vec![ @@ -100,6 +111,7 @@ mod tests { vec_string!["a", "aa"], vec_string!["aa", "a"], vec_string!["a", "a", "a"], - ]); + ] + ); } } diff --git a/src/n0132_palindrome_partitioning_ii.rs b/src/n0132_palindrome_partitioning_ii.rs index ce4149b3..99dc13f0 100644 --- a/src/n0132_palindrome_partitioning_ii.rs +++ b/src/n0132_palindrome_partitioning_ii.rs @@ -2,46 +2,48 @@ * [132] Palindrome Partitioning II * * Given a string s, partition s such that every substring of the partition is a palindrome. - * + * * Return the minimum cuts needed for a palindrome partitioning of s. - * + * * Example: - * - * + * + * * Input: "aab" * Output: 1 * Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. - * - * + * + * */ pub struct Solution {} // submission codes start here /* - 为了方便讨论, 我们记 n 个字符的最少回文分段是 f(n), 则切分次数为 f(n)-1, 接下来递推 f(n): +为了方便讨论, 我们记 n 个字符的最少回文分段是 f(n), 则切分次数为 f(n)-1, 接下来递推 f(n): - f(n) = min(f(n-i) + 1) { i in [0..n] and s[i..n] is palindrome } +f(n) = min(f(n-i) + 1) { i in [0..n] and s[i..n] is palindrome } - 显然, f(1) 为 1, f(0) 为 0 +显然, f(1) 为 1, f(0) 为 0 - 判断 is_palindrome 也需要优化, 使用一个备忘录, 将判断回文的操作优化到 O(1): +判断 is_palindrome 也需要优化, 使用一个备忘录, 将判断回文的操作优化到 O(1): - is_palindrome(s[i..n]) = s[i] == s[n] && is_palindrome(s[i+1..n-1]) +is_palindrome(s[i..n]) = s[i] == s[n] && is_palindrome(s[i+1..n-1]) - 最后的复杂度: 时间 O(N^2), 空间 O(N^2) - */ +最后的复杂度: 时间 O(N^2), 空间 O(N^2) +*/ impl Solution { pub fn min_cut(s: String) -> i32 { let s = s.chars().collect::>(); - if s.is_empty() { return 0 } + if s.is_empty() { + return 0; + } let mut palindrome_cache: Vec>> = vec![vec![None; s.len()]; s.len()]; - let mut min = Vec::with_capacity(s.len()+1); + let mut min = Vec::with_capacity(s.len() + 1); min.push(0); min.push(1); for i in 1..s.len() { let mut local_min = i32::max_value(); - for j in 0..i+1 { + for j in 0..i + 1 { if Solution::is_palindrome(&mut palindrome_cache, &s, j, i) { local_min = i32::min(1 + min[j], local_min); } @@ -51,12 +53,20 @@ impl Solution { min[s.len()] - 1 } - fn is_palindrome(cache: &mut Vec>>, s: &Vec, i: usize, j: usize) -> bool { - if j <= i { return true } + fn is_palindrome( + cache: &mut Vec>>, + s: &Vec, + i: usize, + j: usize, + ) -> bool { + if j <= i { + return true; + } if let Some(result) = cache[i][j] { result } else { - let result = s[i] == s[j] && (i + 1 > s.len() || j < 1 || Solution::is_palindrome(cache, s, i+1, j-1)); + let result = s[i] == s[j] + && (i + 1 > s.len() || j < 1 || Solution::is_palindrome(cache, s, i + 1, j - 1)); cache[i][j] = Some(result); result } diff --git a/src/n0134_gas_station.rs b/src/n0134_gas_station.rs index d8651433..69462797 100644 --- a/src/n0134_gas_station.rs +++ b/src/n0134_gas_station.rs @@ -2,28 +2,28 @@ * [134] Gas Station * * There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. - * + * * You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. - * + * * Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. - * + * * Note: - * - * + * + * * If there exists a solution, it is guaranteed to be unique. * Both input arrays are non-empty and have the same length. * Each element in the input arrays is a non-negative integer. - * - * + * + * * Example 1: - * - * - * Input: + * + * + * Input: * gas = [1,2,3,4,5] * cost = [3,4,5,1,2] - * + * * Output: 3 - * + * * Explanation: * Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 * Travel to station 4. Your tank = 4 - 1 + 5 = 8 @@ -32,17 +32,17 @@ * Travel to station 2. Your tank = 6 - 4 + 3 = 5 * Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. * Therefore, return 3 as the starting index. - * - * + * + * * Example 2: - * - * - * Input: + * + * + * Input: * gas = [2,3,4] * cost = [3,4,3] - * + * * Output: -1 - * + * * Explanation: * You can't start at station 0 or 1, as there is not enough gas to travel to the next station. * Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 @@ -50,8 +50,8 @@ * Travel to station 1. Your tank = 3 - 3 + 3 = 3 * You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. * Therefore, you can't travel around the circuit once no matter where you start. - * - * + * + * */ pub struct Solution {} @@ -70,6 +70,5 @@ mod tests { use super::*; #[test] - fn test_134() { - } + fn test_134() {} } diff --git a/src/n0135_candy.rs b/src/n0135_candy.rs index 10813843..39e3de36 100644 --- a/src/n0135_candy.rs +++ b/src/n0135_candy.rs @@ -2,33 +2,33 @@ * [135] Candy * * There are N children standing in a line. Each child is assigned a rating value. - * + * * You are giving candies to these children subjected to the following requirements: - * - * + * + * * Each child must have at least one candy. * Children with a higher rating get more candies than their neighbors. - * - * + * + * * What is the minimum candies you must give? - * + * * Example 1: - * - * + * + * * Input: [1,0,2] * Output: 5 * Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. - * - * + * + * * Example 2: - * - * + * + * * Input: [1,2,2] * Output: 4 * Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. * The third child gets 1 candy because it satisfies the above two conditions. - * - * + * + * */ pub struct Solution {} @@ -41,11 +41,11 @@ impl Solution { let mut last = 1; let mut ascending = false; for i in 1..ratings.len() { - if ratings[i] == ratings[i-1] { + if ratings[i] == ratings[i - 1] { n += 1; from = i; ascending = false; - } else if ratings[i] >= ratings[i-1] { + } else if ratings[i] >= ratings[i - 1] { from = i; ascending = true; last += 1; @@ -71,11 +71,11 @@ mod tests { #[test] fn test_135() { - assert_eq!(Solution::candy(vec![3,2,1,2,3]), 11); - assert_eq!(Solution::candy(vec![2,2,1,2,2]), 7); - assert_eq!(Solution::candy(vec![1,0,2]), 5); - assert_eq!(Solution::candy(vec![1,2,2]), 4); - assert_eq!(Solution::candy(vec![1,1,1,1,1,1]), 6); - assert_eq!(Solution::candy(vec![1,2,2,2,2,2,2,0]), 10); + assert_eq!(Solution::candy(vec![3, 2, 1, 2, 3]), 11); + assert_eq!(Solution::candy(vec![2, 2, 1, 2, 2]), 7); + assert_eq!(Solution::candy(vec![1, 0, 2]), 5); + assert_eq!(Solution::candy(vec![1, 2, 2]), 4); + assert_eq!(Solution::candy(vec![1, 1, 1, 1, 1, 1]), 6); + assert_eq!(Solution::candy(vec![1, 2, 2, 2, 2, 2, 2, 0]), 10); } } diff --git a/src/n0139_word_break.rs b/src/n0139_word_break.rs index d8d495f9..ed4af30c 100644 --- a/src/n0139_word_break.rs +++ b/src/n0139_word_break.rs @@ -2,51 +2,51 @@ * [139] Word Break * * Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. - * + * * Note: - * - * + * + * * The same word in the dictionary may be reused multiple times in the segmentation. * You may assume the dictionary does not contain duplicate words. - * - * + * + * * Example 1: - * - * + * + * * Input: s = "leetcode", wordDict = ["leet", "code"] * Output: true * Explanation: Return true because "leetcode" can be segmented as "leet code". - * - * + * + * * Example 2: - * - * + * + * * Input: s = "applepenapple", wordDict = ["apple", "pen"] * Output: true * Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". * Note that you are allowed to reuse a dictionary word. - * - * + * + * * Example 3: - * - * + * + * * Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] * Output: false - * - * + * + * */ pub struct Solution {} /* - 记 f[n] 表示从 0 开始长度为 n 的 substring 是否可以被组成,那么: +记 f[n] 表示从 0 开始长度为 n 的 substring 是否可以被组成,那么: - f[n] = f[k] && (s[k..n] in dict) - f[0] = true +f[n] = f[k] && (s[k..n] in dict) +f[0] = true - DP 向上递推即可 +DP 向上递推即可 - BFS 也是可以的 - */ +BFS 也是可以的 +*/ // submission codes start here @@ -54,9 +54,9 @@ use std::collections::HashSet; impl Solution { pub fn word_break(s: String, word_dict: Vec) -> bool { let word_dict = word_dict.into_iter().collect::>(); - let mut dp = vec![false; s.len()+1]; + let mut dp = vec![false; s.len() + 1]; dp[0] = true; - for i in 1..s.len()+1 { + for i in 1..s.len() + 1 { for j in 0..s.len() { if dp[j] && word_dict.contains(&s[j..i]) { dp[i] = true; @@ -75,7 +75,16 @@ mod tests { #[test] fn test_139() { - assert_eq!(Solution::word_break("leetcode".to_owned(), vec_string!["leet", "code"]), true); - assert_eq!(Solution::word_break("catsandog".to_owned(), vec_string!["cats", "dog", "sand", "and", "cat"]), false); + assert_eq!( + Solution::word_break("leetcode".to_owned(), vec_string!["leet", "code"]), + true + ); + assert_eq!( + Solution::word_break( + "catsandog".to_owned(), + vec_string!["cats", "dog", "sand", "and", "cat"] + ), + false + ); } } diff --git a/src/n0140_word_break_ii.rs b/src/n0140_word_break_ii.rs index de1a76ce..9953e574 100644 --- a/src/n0140_word_break_ii.rs +++ b/src/n0140_word_break_ii.rs @@ -2,17 +2,17 @@ * [140] Word Break II * * Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. - * + * * Note: - * - * + * + * * The same word in the dictionary may be reused multiple times in the segmentation. * You may assume the dictionary does not contain duplicate words. - * - * + * + * * Example 1: - * - * + * + * * Input: * s = "catsanddog" * wordDict = ["cat", "cats", "and", "sand", "dog"] @@ -21,11 +21,11 @@ * "cats and dog", * "cat sand dog" * ] - * - * + * + * * Example 2: - * - * + * + * * Input: * s = "pineapplepenapple" * wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] @@ -36,17 +36,17 @@ * "pine applepen apple" * ] * Explanation: Note that you are allowed to reuse a dictionary word. - * - * + * + * * Example 3: - * - * + * + * * Input: * s = "catsandog" * wordDict = ["cats", "dog", "sand", "and", "cat"] * Output: * [] - * + * */ pub struct Solution {} @@ -65,6 +65,5 @@ mod tests { use super::*; #[test] - fn test_140() { - } + fn test_140() {} } diff --git a/src/n0143_reorder_list.rs b/src/n0143_reorder_list.rs index 59b113ec..169c44d1 100644 --- a/src/n0143_reorder_list.rs +++ b/src/n0143_reorder_list.rs @@ -3,33 +3,33 @@ * * Given a singly linked list L: L0→L1→…→Ln-1→Ln,
* reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… - * + * * You may not modify the values in the list's nodes, only nodes itself may be changed. - * + * * Example 1: - * - * + * + * * Given 1->2->3->4, reorder it to 1->4->2->3. - * + * * Example 2: - * - * + * + * * Given 1->2->3->4->5, reorder it to 1->5->2->4->3. - * - * + * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here /* - 1->2->3->4->5 + 1->2->3->4->5 - 1->2->3<-4<-5 + 1->2->3<-4<-5 - 1->5->2->4->3 - */ + 1->5->2->4->3 +*/ impl Solution { pub fn reorder_list(head: &mut Option>) { // TODO @@ -43,6 +43,5 @@ mod tests { use super::*; #[test] - fn test_143() { - } + fn test_143() {} } diff --git a/src/n0144_binary_tree_preorder_traversal.rs b/src/n0144_binary_tree_preorder_traversal.rs index 444b4ca1..951014c6 100644 --- a/src/n0144_binary_tree_preorder_traversal.rs +++ b/src/n0144_binary_tree_preorder_traversal.rs @@ -2,30 +2,30 @@ * [144] Binary Tree Preorder Traversal * * Given a binary tree, return the preorder traversal of its nodes' values. - * + * * Example: - * - * + * + * * Input: [1,null,2,3] * 1 * \ * 2 * / * 3 - * + * * Output: [1,2,3] - * - * + * + * * Follow up: Recursive solution is trivial, could you do it iteratively? - * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn preorder_traversal(root: Option>>) -> Vec { let mut res = Vec::new(); @@ -50,6 +50,9 @@ mod tests { #[test] fn test_144() { - assert_eq!(Solution::preorder_traversal(tree![1,null,2,3]), vec![1,2,3]); + assert_eq!( + Solution::preorder_traversal(tree![1, null, 2, 3]), + vec![1, 2, 3] + ); } } diff --git a/src/n0145_binary_tree_postorder_traversal.rs b/src/n0145_binary_tree_postorder_traversal.rs index 681229c1..66495658 100644 --- a/src/n0145_binary_tree_postorder_traversal.rs +++ b/src/n0145_binary_tree_postorder_traversal.rs @@ -2,30 +2,30 @@ * [145] Binary Tree Postorder Traversal * * Given a binary tree, return the postorder traversal of its nodes' values. - * + * * Example: - * - * + * + * * Input: [1,null,2,3] * 1 * \ * 2 * / * 3 - * + * * Output: [3,2,1] - * - * + * + * * Follow up: Recursive solution is trivial, could you do it iteratively? - * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn postorder_traversal(root: Option>>) -> Vec { let mut res = Vec::new(); @@ -50,6 +50,9 @@ mod tests { #[test] fn test_145() { - assert_eq!(Solution::postorder_traversal(tree![1,null,2,3]), vec![3,2,1]); + assert_eq!( + Solution::postorder_traversal(tree![1, null, 2, 3]), + vec![3, 2, 1] + ); } } diff --git a/src/n0146_lru_cache.rs b/src/n0146_lru_cache.rs index 84445af1..5ee256c8 100644 --- a/src/n0146_lru_cache.rs +++ b/src/n0146_lru_cache.rs @@ -1,22 +1,22 @@ /** * [146] LRU Cache * - * + * * Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. - * - * - * + * + * + * * get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
* put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. - * - * + * + * * Follow up:
* Could you do both operations in O(1) time complexity? - * + * * Example: - * + * * LRUCache cache = new LRUCache( 2 /* capacity */ ); - * + * * cache.put(1, 1); * cache.put(2, 2); * cache.get(1); // returns 1 @@ -26,22 +26,21 @@ * cache.get(1); // returns -1 (not found) * cache.get(3); // returns 3 * cache.get(4); // returns 4 - * - * + * + * */ - // submission codes start here /* - Least Recently Used, 最近最少使用, 关键在于追踪每一个 entry 的 age, 每次淘汰最小的那一个 key +Least Recently Used, 最近最少使用, 关键在于追踪每一个 entry 的 age, 每次淘汰最小的那一个 key - 假如淘汰逻辑要做到 O(1) 复杂度, 我们可以引入一个链表, 每次 touch 一个值时, 就删掉它重新 push_back, 而当达到容量要驱逐时, 则 pop_front +假如淘汰逻辑要做到 O(1) 复杂度, 我们可以引入一个链表, 每次 touch 一个值时, 就删掉它重新 push_back, 而当达到容量要驱逐时, 则 pop_front - Rust 的链表不支持根据引用删除任意元素,也没有 LinkedHashMap,需要自己实现一个 - */ +Rust 的链表不支持根据引用删除任意元素,也没有 LinkedHashMap,需要自己实现一个 +*/ use std::collections::HashMap; -use std::ptr; use std::mem; +use std::ptr; // Entry is either a map entry and a link-list node pub struct LRUEntry { @@ -53,7 +52,7 @@ pub struct LRUEntry { impl LRUEntry { pub fn new(key: i32, val: i32) -> Self { - LRUEntry{ + LRUEntry { key: key, val: val, prev: ptr::null_mut(), @@ -75,7 +74,7 @@ impl LRUCache { pub fn new(capacity: i32) -> Self { let capacity = capacity as usize; let map = HashMap::with_capacity(capacity); - let cache = LRUCache{ + let cache = LRUCache { map: map, cap: capacity, head: unsafe { Box::into_raw(Box::new(mem::uninitialized::())) }, @@ -88,7 +87,7 @@ impl LRUCache { cache } - + pub fn get(&mut self, key: i32) -> i32 { let (ptr, val) = match self.map.get_mut(&key) { None => (None, None), @@ -104,7 +103,7 @@ impl LRUCache { } val.unwrap_or(-1) } - + pub fn put(&mut self, key: i32, value: i32) { let ptr = self.map.get_mut(&key).map(|entry| { let ptr: *mut LRUEntry = &mut **entry; @@ -141,7 +140,7 @@ impl LRUCache { unsafe { next = (*self.head).next } // list is empty if next == self.tail { - return None + return None; } let key = unsafe { (*next).key }; let mut old_entry = self.map.remove(&key).unwrap(); @@ -180,20 +179,19 @@ mod tests { #[test] fn test_146() { - println!("init cache"); let mut lru_cache = LRUCache::new(2); lru_cache.put(1, 1); lru_cache.put(2, 2); println!("return 1"); - assert_eq!(lru_cache.get(1), 1); // returns 1 + assert_eq!(lru_cache.get(1), 1); // returns 1 println!("evict key 2"); - lru_cache.put(3, 3); // evicts key 2 + lru_cache.put(3, 3); // evicts key 2 println!("return -1"); - assert_eq!(lru_cache.get(2), -1); // returns -1 (not found) - lru_cache.put(4, 4); // evicts key 1 - assert_eq!(lru_cache.get(1), -1); // returns -1 (not found) - assert_eq!(lru_cache.get(3), 3); // returns 3 - assert_eq!(lru_cache.get(4), 4); // returns 4 + assert_eq!(lru_cache.get(2), -1); // returns -1 (not found) + lru_cache.put(4, 4); // evicts key 1 + assert_eq!(lru_cache.get(1), -1); // returns -1 (not found) + assert_eq!(lru_cache.get(3), 3); // returns 3 + assert_eq!(lru_cache.get(4), 4); // returns 4 } } diff --git a/src/n0147_insertion_sort_list.rs b/src/n0147_insertion_sort_list.rs index 76617241..edcd0787 100644 --- a/src/n0147_insertion_sort_list.rs +++ b/src/n0147_insertion_sort_list.rs @@ -2,44 +2,44 @@ * [147] Insertion Sort List * * Sort a linked list using insertion sort. - * + * *
    *
- * + * *
* A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
* With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list

* - * + * *
    *
- * + * * Algorithm of Insertion Sort: - * + * *
    * Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. * At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. * It repeats until no input elements remain. *
- * + * *
* Example 1: - * - * + * + * * Input: 4->2->1->3 * Output: 1->2->3->4 - * - * + * + * * Example 2: - * - * + * + * * Input: -1->5->3->4->0 * Output: -1->0->3->4->5 - * - * + * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here @@ -57,6 +57,5 @@ mod tests { use super::*; #[test] - fn test_147() { - } + fn test_147() {} } diff --git a/src/n0148_sort_list.rs b/src/n0148_sort_list.rs index 1ab84ac5..5fd6a8a2 100644 --- a/src/n0148_sort_list.rs +++ b/src/n0148_sort_list.rs @@ -2,41 +2,41 @@ * [148] Sort List * * Sort a linked list in O(n log n) time using constant space complexity. - * + * * Example 1: - * - * + * + * * Input: 4->2->1->3 * Output: 1->2->3->4 - * - * + * + * * Example 2: - * - * + * + * * Input: -1->5->3->4->0 * Output: -1->0->3->4->5 - * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here /* - 堆排序需要额外空间, 不行 +堆排序需要额外空间, 不行 - 快排: - * 不行, 单链表要快排必须同时持有两个 mut 引用, 而 rust 里这是不可能的(不知道用 unsafe 行不行) - * 不用 rust 的话应该是可行的, Lomuto-partition, 用一个慢指针记录 no_lager_than 位置 +快排: + * 不行, 单链表要快排必须同时持有两个 mut 引用, 而 rust 里这是不可能的(不知道用 unsafe 行不行) + * 不用 rust 的话应该是可行的, Lomuto-partition, 用一个慢指针记录 no_lager_than 位置 - 归并,有点慢, 每次切分要遍历找到切分点, 而且递归栈深度 O(logN) 也不算严格的 O(1) 空间 +归并,有点慢, 每次切分要遍历找到切分点, 而且递归栈深度 O(logN) 也不算严格的 O(1) 空间 - Rust 标准库的 std::collections::LinkedList 都没有实现 sort() 你敢信... +Rust 标准库的 std::collections::LinkedList 都没有实现 sort() 你敢信... - 这题用 rust 解对我而言真的是 Hard 级而不是 Medium 级了... +这题用 rust 解对我而言真的是 Hard 级而不是 Medium 级了... - 这里也是前置知识不足, GG 了解到链表的最佳排序方式确实就是 merge-sort - */ +这里也是前置知识不足, GG 了解到链表的最佳排序方式确实就是 merge-sort +*/ impl Solution { pub fn sort_list(mut head: Option>) -> Option> { let mut len = 0; @@ -57,14 +57,17 @@ impl Solution { while i < len / 2 { next = next.unwrap().next.as_mut(); i += 1; - }; + } let mut l2 = next.unwrap().next.take(); - let mut l1 = Solution::merge_sort(head, len/2); - let mut l2 = Solution::merge_sort(l2, len - len/2); + let mut l1 = Solution::merge_sort(head, len / 2); + let mut l2 = Solution::merge_sort(l2, len - len / 2); Solution::merge(l1, l2) } - fn merge(mut l1: Option>, mut l2: Option>) -> Option> { + fn merge( + mut l1: Option>, + mut l2: Option>, + ) -> Option> { let mut dummy = Some(Box::new(ListNode::new(0))); let mut next = dummy.as_mut(); loop { @@ -72,20 +75,26 @@ impl Solution { (Some(mut node1), Some(mut node2)) => { let node = if node1.val > node2.val { // give back ownership - l2 = node2.next.take(); l1 = Some(node1); node2 + l2 = node2.next.take(); + l1 = Some(node1); + node2 } else { - l1 = node1.next.take(); l2 = Some(node2); node1 + l1 = node1.next.take(); + l2 = Some(node2); + node1 }; next.as_mut().unwrap().next = Some(node); next = next.unwrap().next.as_mut(); - }, + } (Some(mut node1), None) => { - next.unwrap().next = Some(node1); break - }, + next.unwrap().next = Some(node1); + break; + } (None, Some(mut node2)) => { - next.unwrap().next = Some(node2); break - }, - (None, None) => { break }, + next.unwrap().next = Some(node2); + break; + } + (None, None) => break, } } dummy.unwrap().next @@ -100,8 +109,14 @@ mod tests { #[test] fn test_148() { - assert_eq!(Solution::sort_list(linked![4,2,1,3]), linked![1,2,3,4]); - assert_eq!(Solution::sort_list(linked![-1,5,3,4,0]), linked![-1,0,3,4,5]); + assert_eq!( + Solution::sort_list(linked![4, 2, 1, 3]), + linked![1, 2, 3, 4] + ); + assert_eq!( + Solution::sort_list(linked![-1, 5, 3, 4, 0]), + linked![-1, 0, 3, 4, 5] + ); assert_eq!(Solution::sort_list(linked![]), linked![]); } } diff --git a/src/n0149_max_points_on_a_line.rs b/src/n0149_max_points_on_a_line.rs index 35b8e744..dff94777 100644 --- a/src/n0149_max_points_on_a_line.rs +++ b/src/n0149_max_points_on_a_line.rs @@ -2,10 +2,10 @@ * [149] Max Points on a Line * * Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. - * + * * Example 1: - * - * + * + * * Input: [[1,1],[2,2],[3,3]] * Output: 3 * Explanation: @@ -16,11 +16,11 @@ * | o * +-------------> * 0 1 2 3 4 - * - * + * + * * Example 2: - * - * + * + * * Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] * Output: 4 * Explanation: @@ -32,30 +32,30 @@ * | o o * +-------------------> * 0 1 2 3 4 5 6 - * - * + * + * */ pub struct Solution {} use super::util::point::Point; /* - 要回顾下高中数学:已知两点, 求解一般式: +要回顾下高中数学:已知两点, 求解一般式: - * Ax + By + C = 0 - * A = y2 - y1, B = x1 - x2, C = x2y1 - x1y2 + * Ax + By + C = 0 + * A = y2 - y1, B = x1 - x2, C = x2y1 - x1y2 - 有这个知识之后,化为一般式,做三层遍历就行,再加上一个 HashSet,避免对同一直线上点的重复计算,时间复杂度可以是 O(N^2) +有这个知识之后,化为一般式,做三层遍历就行,再加上一个 HashSet,避免对同一直线上点的重复计算,时间复杂度可以是 O(N^2) - 有两个坑要注意避免: +有两个坑要注意避免: - * 给的 case 会导致 i32 溢出,这里直接用了 i64 表示 - * 给的 case 里有相同的点,直接处理相同点的话会导致最坏情况复杂度到 O(N^3),因此要先做一次转化,归并相同的点 + * 给的 case 会导致 i32 溢出,这里直接用了 i64 表示 + * 给的 case 里有相同的点,直接处理相同点的话会导致最坏情况复杂度到 O(N^3),因此要先做一次转化,归并相同的点 - 用 Rust 实现有另一点注意的,给的 Point 没有实现 Hash Trait,要自己转化一下 - */ +用 Rust 实现有另一点注意的,给的 Point 没有实现 Hash Trait,要自己转化一下 +*/ // straight-line expression: Ax + By + C = 0 // A = y2 - y1, B = x1 - x2, C = x2y1 - x1y2 -#[derive(PartialEq,Hash,Eq,Debug)] +#[derive(PartialEq, Hash, Eq, Debug)] struct Line(i64, i64, i64); impl Line { @@ -65,40 +65,42 @@ impl Line { let x2 = p2.x as i64; let y1 = p1.y as i64; let y2 = p2.y as i64; - Line(y2-y1, x1-x2, x2*y1 - x1*y2) + Line(y2 - y1, x1 - x2, x2 * y1 - x1 * y2) } fn contains(&self, p: &Point) -> bool { self.0 * p.x as i64 + self.1 * p.y as i64 + self.2 == 0_i64 } } -use std::collections::HashSet; use std::collections::HashMap; +use std::collections::HashSet; impl Solution { pub fn max_points(points: Vec) -> i32 { // fold same point, record the point count - let points: Vec<(Point, i32)> = points.into_iter() + let points: Vec<(Point, i32)> = points + .into_iter() .fold(HashMap::new(), |mut map, v| { - *map.entry((v.x, v.y)).or_insert(0) += 1; map + *map.entry((v.x, v.y)).or_insert(0) += 1; + map }) .into_iter() - .map(|(k,v)| { (Point::new(k.0, k.1), v) }) // Point did not implement Hash trait + .map(|(k, v)| (Point::new(k.0, k.1), v)) // Point did not implement Hash trait .collect(); // any two points in a straight-line, return quickly if points.len() < 3 { - return points.into_iter().fold(0, |acc, v| { acc + v.1 }); + return points.into_iter().fold(0, |acc, v| acc + v.1); } let mut max = 2; let mut set: HashSet = HashSet::new(); - for i in 0..(points.len()-1) { - for j in i+1..points.len() { + for i in 0..(points.len() - 1) { + for j in i + 1..points.len() { let line = Line::new(&points[i].0, &points[j].0); if set.contains(&line) { continue; } let mut curr = points[i].1 + points[j].1; - for k in j+1..points.len() { + for k in j + 1..points.len() { if line.contains(&points[k].0) { curr += points[k].1; } @@ -119,19 +121,52 @@ mod tests { #[test] fn test_149() { assert_eq!( - Solution::max_points(vec![point![1,1],point![2,2],point![3,3]]), - 3); + Solution::max_points(vec![point![1, 1], point![2, 2], point![3, 3]]), + 3 + ); assert_eq!( - Solution::max_points(vec![point![1,1],point![3,2],point![5,3],point![4,1],point![2,3],point![1,4]]), - 4); + Solution::max_points(vec![ + point![1, 1], + point![3, 2], + point![5, 3], + point![4, 1], + point![2, 3], + point![1, 4] + ]), + 4 + ); assert_eq!( - Solution::max_points(vec![point![0,0],point![1,65536],point![65536,0]]), - 2); + Solution::max_points(vec![point![0, 0], point![1, 65536], point![65536, 0]]), + 2 + ); assert_eq!( - Solution::max_points(vec![point![1,1],point![1,1],point![1,1]]), - 3); + Solution::max_points(vec![point![1, 1], point![1, 1], point![1, 1]]), + 3 + ); assert_eq!( - Solution::max_points(vec![point![0,9],point![138,429],point![115,359],point![115,359],point![-30,-102],point![230,709],point![-150,-686],point![-135,-613],point![-60,-248],point![-161,-481],point![207,639],point![23,79],point![-230,-691],point![-115,-341],point![92,289],point![60,336],point![-105,-467],point![135,701],point![-90,-394],point![-184,-551],point![150,774]]), + Solution::max_points(vec![ + point![0, 9], + point![138, 429], + point![115, 359], + point![115, 359], + point![-30, -102], + point![230, 709], + point![-150, -686], + point![-135, -613], + point![-60, -248], + point![-161, -481], + point![207, 639], + point![23, 79], + point![-230, -691], + point![-115, -341], + point![92, 289], + point![60, 336], + point![-105, -467], + point![135, 701], + point![-90, -394], + point![-184, -551], + point![150, 774] + ]), 12 ) } diff --git a/src/n0150_evaluate_reverse_polish_notation.rs b/src/n0150_evaluate_reverse_polish_notation.rs index 4ceb55eb..4626d5aa 100644 --- a/src/n0150_evaluate_reverse_polish_notation.rs +++ b/src/n0150_evaluate_reverse_polish_notation.rs @@ -2,38 +2,38 @@ * [150] Evaluate Reverse Polish Notation * * Evaluate the value of an arithmetic expression in Reverse Polish Notation. - * + * * Valid operators are +, -, *, /. Each operand may be an integer or another expression. - * + * * Note: - * - * + * + * * Division between two integers should truncate toward zero. * The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation. - * - * + * + * * Example 1: - * - * + * + * * Input: ["2", "1", "+", "3", "*"] * Output: 9 * Explanation: ((2 + 1) * 3) = 9 - * - * + * + * * Example 2: - * - * + * + * * Input: ["4", "13", "5", "/", "+"] * Output: 6 * Explanation: (4 + (13 / 5)) = 6 - * - * + * + * * Example 3: - * - * + * + * * Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] * Output: 22 - * Explanation: + * Explanation: * ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 * = ((10 * (6 / (12 * -11))) + 17) + 5 * = ((10 * (6 / -132)) + 17) + 5 @@ -41,8 +41,8 @@ * = (0 + 17) + 5 * = 17 + 5 * = 22 - * - * + * + * */ pub struct Solution {} @@ -58,11 +58,11 @@ impl Solution { let right = stack.pop().unwrap(); let left = stack.pop().unwrap(); match (t as &str) { - "*" => { stack.push(left * right) }, - "+" => { stack.push(left + right) }, - "/" => { stack.push(left / right) }, - "-" => { stack.push(left - right) }, - _ => { unreachable!() }, + "*" => stack.push(left * right), + "+" => stack.push(left + right), + "/" => stack.push(left / right), + "-" => stack.push(left - right), + _ => unreachable!(), } } } @@ -79,7 +79,9 @@ mod tests { #[test] fn test_150() { assert_eq!( - Solution::eval_rpn(vec_string!["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]), + Solution::eval_rpn(vec_string![ + "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" + ]), 22 ); } diff --git a/src/n0151_reverse_words_in_a_string.rs b/src/n0151_reverse_words_in_a_string.rs index 1c8292d8..e26bd573 100644 --- a/src/n0151_reverse_words_in_a_string.rs +++ b/src/n0151_reverse_words_in_a_string.rs @@ -2,46 +2,46 @@ * [151] Reverse Words in a String * * Given an input string, reverse the string word by word. - * + * * - * + * * Example 1: - * - * + * + * * Input: "the sky is blue" * Output: "blue is sky the" - * - * + * + * * Example 2: - * - * + * + * * Input: " hello world! " * Output: "world! hello" * Explanation: Your reversed string should not contain leading or trailing spaces. - * - * + * + * * Example 3: - * - * + * + * * Input: "a good example" * Output: "example good a" * Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. - * - * + * + * * - * + * * Note: - * - * + * + * * A word is defined as a sequence of non-space characters. * Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. * You need to reduce multiple spaces between two words to a single space in the reversed string. - * - * + * + * * - * + * * Follow up: - * + * * For C programmers, try to solve it in-place in O(1) extra space. */ pub struct Solution {} @@ -78,7 +78,13 @@ mod tests { #[test] fn test_151() { - assert_eq!(Solution::reverse_words("the sky is blue".to_owned()), "blue is sky the".to_owned()); - assert_eq!(Solution::reverse_words(" hello world! ".to_owned()), "world! hello".to_owned()); + assert_eq!( + Solution::reverse_words("the sky is blue".to_owned()), + "blue is sky the".to_owned() + ); + assert_eq!( + Solution::reverse_words(" hello world! ".to_owned()), + "world! hello".to_owned() + ); } } diff --git a/src/n0152_maximum_product_subarray.rs b/src/n0152_maximum_product_subarray.rs index 6aa2299c..34bba87e 100644 --- a/src/n0152_maximum_product_subarray.rs +++ b/src/n0152_maximum_product_subarray.rs @@ -2,40 +2,40 @@ * [152] Maximum Product Subarray * * Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. - * + * * Example 1: - * - * + * + * * Input: [2,3,-2,4] * Output: 6 * Explanation: [2,3] has the largest product 6. - * - * + * + * * Example 2: - * - * + * + * * Input: [-2,0,-1] * Output: 0 * Explanation: The result cannot be 2, because [-2,-1] is not a subarray. - * + * */ pub struct Solution {} // submission codes start here /* - f[i], g[i] means the max positive value and max negative value for the sub-seq end with index i +f[i], g[i] means the max positive value and max negative value for the sub-seq end with index i - then we have: +then we have: - f[i], g[i] = if nums[i] == 0 { - 0, 0 - } else if nums[i] > 0 { - f[i-1] * nums[i], g[i-1] * nums[i] - } else if nums[i] < 0 { - g[i-1] * nums[i], f[i-1] * nums[i] - } - */ +f[i], g[i] = if nums[i] == 0 { + 0, 0 +} else if nums[i] > 0 { + f[i-1] * nums[i], g[i-1] * nums[i] +} else if nums[i] < 0 { + g[i-1] * nums[i], f[i-1] * nums[i] +} +*/ impl Solution { pub fn max_product(nums: Vec) -> i32 { @@ -44,13 +44,16 @@ impl Solution { let mut pos_max = 0; for num in nums.into_iter() { if num == 0 { - neg_max = 0; pos_max = 0; + neg_max = 0; + pos_max = 0; max = i32::max(max, 0); } else if num > 0 { - pos_max = i32::max(pos_max * num, num); neg_max = neg_max * num; + pos_max = i32::max(pos_max * num, num); + neg_max = neg_max * num; } else { let pos_pre = pos_max; - pos_max = neg_max * num; neg_max = i32::min(pos_pre * num, num); + pos_max = neg_max * num; + neg_max = i32::min(pos_pre * num, num); } if pos_max != 0 { max = i32::max(max, pos_max); @@ -68,8 +71,8 @@ mod tests { #[test] fn test_152() { - assert_eq!(Solution::max_product(vec![2,3,-2,4]), 6); - assert_eq!(Solution::max_product(vec![-2,0,-1]), 0); - assert_eq!(Solution::max_product(vec![-4,-3,-2]), 12); + assert_eq!(Solution::max_product(vec![2, 3, -2, 4]), 6); + assert_eq!(Solution::max_product(vec![-2, 0, -1]), 0); + assert_eq!(Solution::max_product(vec![-4, -3, -2]), 12); } } diff --git a/src/n0153_find_minimum_in_rotated_sorted_array.rs b/src/n0153_find_minimum_in_rotated_sorted_array.rs index 0b4fc49f..9c609f42 100644 --- a/src/n0153_find_minimum_in_rotated_sorted_array.rs +++ b/src/n0153_find_minimum_in_rotated_sorted_array.rs @@ -2,27 +2,27 @@ * [153] Find Minimum in Rotated Sorted Array * * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. - * + * * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). - * + * * Find the minimum element. - * + * * You may assume no duplicate exists in the array. - * + * * Example 1: - * - * - * Input: [3,4,5,1,2] + * + * + * Input: [3,4,5,1,2] * Output: 1 - * - * + * + * * Example 2: - * - * + * + * * Input: [4,5,6,7,0,1,2] * Output: 0 - * - * + * + * */ pub struct Solution {} @@ -31,7 +31,9 @@ pub struct Solution {} impl Solution { pub fn find_min(nums: Vec) -> i32 { let mut size = nums.len(); - if size == 0 { return -1 } + if size == 0 { + return -1; + } let mut base = 0_usize; while size > 1 { let half = size / 2; @@ -53,7 +55,7 @@ mod tests { #[test] fn test_153() { - assert_eq!(Solution::find_min(vec![4,5,6,1,2,3]), 1); - assert_eq!(Solution::find_min(vec![4,5,6,7,0,1,2]), 0); + assert_eq!(Solution::find_min(vec![4, 5, 6, 1, 2, 3]), 1); + assert_eq!(Solution::find_min(vec![4, 5, 6, 7, 0, 1, 2]), 0); } } diff --git a/src/n0154_find_minimum_in_rotated_sorted_array_ii.rs b/src/n0154_find_minimum_in_rotated_sorted_array_ii.rs index e134d927..8868ff82 100644 --- a/src/n0154_find_minimum_in_rotated_sorted_array_ii.rs +++ b/src/n0154_find_minimum_in_rotated_sorted_array_ii.rs @@ -2,46 +2,46 @@ * [154] Find Minimum in Rotated Sorted Array II * * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. - * + * * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). - * + * * Find the minimum element. - * + * * The array may contain duplicates. - * + * * Example 1: - * - * + * + * * Input: [1,3,5] * Output: 1 - * + * * Example 2: - * - * + * + * * Input: [2,2,2,0,1] * Output: 0 - * + * * Note: - * - * + * + * * This is a follow up problem to Find Minimum in Rotated Sorted Array. * Would allow duplicates affect the run-time complexity? How and why? - * - * + * + * */ pub struct Solution {} // submission codes start here /* - 针对无重复的做法, 只要二分搜索找折点即可: 假如 nums[mid] > nums[base] 那么转折点一定在右侧, 否则在左侧 +针对无重复的做法, 只要二分搜索找折点即可: 假如 nums[mid] > nums[base] 那么转折点一定在右侧, 否则在左侧 - 但假如有重复, 就可能有 nums[mid] == nums[base], 这时就尴尬了, 无法确定转折点在左半部分还是右半部分 +但假如有重复, 就可能有 nums[mid] == nums[base], 这时就尴尬了, 无法确定转折点在左半部分还是右半部分 - 可以考虑一个数组, [1,1,1,1,1,1,1,0,1,1,1,1,1,1] 这个数组无论怎么去找 0, 时间复杂度无法低于 O(N) +可以考虑一个数组, [1,1,1,1,1,1,1,0,1,1,1,1,1,1] 这个数组无论怎么去找 0, 时间复杂度无法低于 O(N) - 但假如不是这种极端情况, 那么二分搜索还是能优化的, 在 153 的基础上, 碰到相等就跳过即可 - */ +但假如不是这种极端情况, 那么二分搜索还是能优化的, 在 153 的基础上, 碰到相等就跳过即可 +*/ impl Solution { pub fn find_min(nums: Vec) -> i32 { let mut lo = 0; @@ -57,7 +57,7 @@ impl Solution { hi -= 1; } } - return nums[lo] + return nums[lo]; } } @@ -69,8 +69,8 @@ mod tests { #[test] fn test_154() { - assert_eq!(Solution::find_min(vec![1,2,2,2,2,2]), 1); - assert_eq!(Solution::find_min(vec![1,3,3]), 1); - assert_eq!(Solution::find_min(vec![3,1,3,3]), 1); + assert_eq!(Solution::find_min(vec![1, 2, 2, 2, 2, 2]), 1); + assert_eq!(Solution::find_min(vec![1, 3, 3]), 1); + assert_eq!(Solution::find_min(vec![3, 1, 3, 3]), 1); } } diff --git a/src/n0155_min_stack.rs b/src/n0155_min_stack.rs index c2e1fe61..1c544d87 100644 --- a/src/n0155_min_stack.rs +++ b/src/n0155_min_stack.rs @@ -1,26 +1,26 @@ /** * [155] Min Stack * - * + * * Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. - * - * + * + * * push(x) -- Push element x onto stack. - * - * + * + * * pop() -- Removes the element on top of the stack. - * - * + * + * * top() -- Get the top element. - * - * + * + * * getMin() -- Retrieve the minimum element in the stack. - * - * - * - * + * + * + * + * * Example:
- * + * * MinStack minStack = new MinStack(); * minStack.push(-2); * minStack.push(0); @@ -29,39 +29,38 @@ * minStack.pop(); * minStack.top(); --> Returns 0. * minStack.getMin(); --> Returns -2. - * - * + * + * */ pub struct Solution {} // submission codes start here /* - 这题居然是 easy... 我怀疑人生了, getMin() 怎么能做到常数时间? Heap 也是 LogN 啊 +这题居然是 easy... 我怀疑人生了, getMin() 怎么能做到常数时间? Heap 也是 LogN 啊 - 看了最高票解之后...........天哪, 我可太菜了 +看了最高票解之后...........天哪, 我可太菜了 - 核心思想是保证每次 pop 时都能以常数时间更新最小值, 这就需要在空间上以某种方式记录下来 +核心思想是保证每次 pop 时都能以常数时间更新最小值, 这就需要在空间上以某种方式记录下来 - 那一种做法就是存储每个元素和最小值之间的差值, 这样 pop 的时候就能不断还原出原始值 +那一种做法就是存储每个元素和最小值之间的差值, 这样 pop 的时候就能不断还原出原始值 - 另一种更直观的做法就是每次入栈 min 时, 都把前一个 min (当前第二小的数字) 放在它前面, 作为记录 - */ +另一种更直观的做法就是每次入栈 min 时, 都把前一个 min (当前第二小的数字) 放在它前面, 作为记录 +*/ struct MinStack { vec: Vec, min: i32, } impl MinStack { - /** initialize your data structure here. */ pub fn new() -> Self { - MinStack{ + MinStack { vec: Vec::new(), min: i32::max_value(), } } - + pub fn push(&mut self, x: i32) { if x <= self.min { self.vec.push(self.min); @@ -75,11 +74,11 @@ impl MinStack { self.min = self.vec.pop().unwrap(); } } - + pub fn top(&self) -> i32 { *self.vec.last().unwrap() } - + pub fn get_min(&self) -> i32 { self.min } @@ -106,9 +105,9 @@ mod tests { min_stack.push(-2); min_stack.push(0); min_stack.push(-3); - assert_eq!(min_stack.get_min(), -3); // --> Returns -3. + assert_eq!(min_stack.get_min(), -3); // --> Returns -3. min_stack.pop(); - assert_eq!(min_stack.top(), 0); // --> Returns 0. - assert_eq!(min_stack.get_min(), -2); // --> Returns -2.[] + assert_eq!(min_stack.top(), 0); // --> Returns 0. + assert_eq!(min_stack.get_min(), -2); // --> Returns -2.[] } } diff --git a/src/n0162_find_peak_element.rs b/src/n0162_find_peak_element.rs index c82ae410..8e5a3f76 100644 --- a/src/n0162_find_peak_element.rs +++ b/src/n0162_find_peak_element.rs @@ -2,33 +2,33 @@ * [162] Find Peak Element * * A peak element is an element that is greater than its neighbors. - * + * * Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. - * + * * The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. - * + * * You may imagine that nums[-1] = nums[n] = -∞. - * + * * Example 1: - * - * + * + * * Input: nums = [1,2,3,1] * Output: 2 * Explanation: 3 is a peak element and your function should return the index number 2. - * + * * Example 2: - * - * + * + * * Input: nums = [1,2,1,3,5,6,4] - * Output: 1 or 5 - * Explanation: Your function can return either index number 1 where the peak element is 2, + * Output: 1 or 5 + * Explanation: Your function can return either index number 1 where the peak element is 2, * or index number 5 where the peak element is 6. - * - * + * + * * Note: - * + * * Your solution should be in logarithmic complexity. - * + * */ pub struct Solution {} @@ -40,7 +40,7 @@ impl Solution { let mut mid = 0; while lo < hi { mid = (hi - lo) / 2 + lo; - if mid + 1 < nums.len() && nums[mid] < nums[mid+1]{ + if mid + 1 < nums.len() && nums[mid] < nums[mid + 1] { lo = mid + 1; } else { hi = mid; @@ -58,7 +58,7 @@ mod tests { #[test] fn test_162() { - assert_eq!(Solution::find_peak_element(vec![1,2,3,1]), 2); - assert_eq!(Solution::find_peak_element(vec![1,2,1,3,5,6,4]), 5); + assert_eq!(Solution::find_peak_element(vec![1, 2, 3, 1]), 2); + assert_eq!(Solution::find_peak_element(vec![1, 2, 1, 3, 5, 6, 4]), 5); } } diff --git a/src/n0164_maximum_gap.rs b/src/n0164_maximum_gap.rs index f8661f96..ded5006d 100644 --- a/src/n0164_maximum_gap.rs +++ b/src/n0164_maximum_gap.rs @@ -2,49 +2,49 @@ * [164] Maximum Gap * * Given an unsorted array, find the maximum difference between the successive elements in its sorted form. - * + * * Return 0 if the array contains less than 2 elements. - * + * * Example 1: - * - * + * + * * Input: [3,6,9,1] * Output: 3 * Explanation: The sorted form of the array is [1,3,6,9], either * (3,6) or (6,9) has the maximum difference 3. - * + * * Example 2: - * - * + * + * * Input: [10] * Output: 0 * Explanation: The array contains less than 2 elements, therefore return 0. - * + * * Note: - * - * + * + * * You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range. * Try to solve it in linear time/space. - * - * + * + * */ pub struct Solution {} // submission codes start here /* - 想不出来, 一看解析居然是 Radix Sort 或 Bucket Sort, 我就 ??? 了... +想不出来, 一看解析居然是 Radix Sort 或 Bucket Sort, 我就 ??? 了... - 最佳算法是 Bucket Sort 吗? (桶大小取 max - min / len 那种), 看时间复杂度好像是这样 +最佳算法是 Bucket Sort 吗? (桶大小取 max - min / len 那种), 看时间复杂度好像是这样 - 但假如整体排布非常稠密, 那么这个聪明的算法也就退化成了桶大小为 1 的桶排序 - */ +但假如整体排布非常稠密, 那么这个聪明的算法也就退化成了桶大小为 1 的桶排序 +*/ impl Solution { pub fn maximum_gap(nums: Vec) -> i32 { let mut nums = nums; nums.sort_unstable(); let mut gap = 0; for i in 1..nums.len() { - gap = i32::max(nums[i] - nums[i-1], gap); + gap = i32::max(nums[i] - nums[i - 1], gap); } gap } @@ -58,6 +58,6 @@ mod tests { #[test] fn test_164() { - assert_eq!(Solution::maximum_gap(vec![3,6,9,1]), 3); + assert_eq!(Solution::maximum_gap(vec![3, 6, 9, 1]), 3); } } diff --git a/src/n0165_compare_version_numbers.rs b/src/n0165_compare_version_numbers.rs index c3a323e8..522224df 100644 --- a/src/n0165_compare_version_numbers.rs +++ b/src/n0165_compare_version_numbers.rs @@ -3,46 +3,46 @@ * * Compare two version numbers version1 and version2.
* If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0. - * + * * You may assume that the version strings are non-empty and contain only digits and the . character. * The . character does not represent a decimal point and is used to separate number sequences. * For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. * You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0. - * + * * - * + * * Example 1: - * + * * Input: version1 = "0.1", version2 = "1.1" * Output: -1 - * + * * Example 2: - * + * * Input: version1 = "1.0.1", version2 = "1" * Output: 1 - * + * * Example 3: - * + * * Input: version1 = "7.5.2.4", version2 = "7.5.3" * Output: -1 - * + * * Example 4: - * + * * Input: version1 = "1.01", version2 = "1.001" * Output: 0 * Explanation: Ignoring leading zeroes, both “01” and “001" represent the same number “1” - * + * * Example 5: - * + * * Input: version1 = "1.0", version2 = "1.0.0" * Output: 0 * Explanation: The first version number does not have a third level revision number, which means its third level revision number is default to "0" - * + * * - * + * * Note: *
    - * Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes. + * Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes. * Version strings do not start or end with dots, and they will not be two consecutive dots. *
*/ @@ -56,12 +56,12 @@ impl Solution { let v2: Vec<&str> = version2.split('.').collect::>(); let mut i = 0_usize; while i < v1.len() && i < v2.len() { - let left = v1[i].parse::().unwrap(); + let left = v1[i].parse::().unwrap(); let right = v2[i].parse::().unwrap(); if left > right { return 1; } else if left < right { - return - 1; + return -1; } i += 1; } @@ -77,7 +77,7 @@ impl Solution { } i += 1; } - return 0 + return 0; } } @@ -89,9 +89,21 @@ mod tests { #[test] fn test_165() { - assert_eq!(Solution::compare_version( "0.1".to_owned(), "1.1".to_owned()), -1); - assert_eq!(Solution::compare_version( "1.0.1".to_owned(), "1".to_owned()), 1); - assert_eq!(Solution::compare_version( "7.5.2.4".to_owned(), "7.5.3".to_owned()), -1); - assert_eq!(Solution::compare_version( "1.01".to_owned(), "1.0001".to_owned()), 0); + assert_eq!( + Solution::compare_version("0.1".to_owned(), "1.1".to_owned()), + -1 + ); + assert_eq!( + Solution::compare_version("1.0.1".to_owned(), "1".to_owned()), + 1 + ); + assert_eq!( + Solution::compare_version("7.5.2.4".to_owned(), "7.5.3".to_owned()), + -1 + ); + assert_eq!( + Solution::compare_version("1.01".to_owned(), "1.0001".to_owned()), + 0 + ); } } diff --git a/src/n0166_fraction_to_recurring_decimal.rs b/src/n0166_fraction_to_recurring_decimal.rs index f2117358..29900b38 100644 --- a/src/n0166_fraction_to_recurring_decimal.rs +++ b/src/n0166_fraction_to_recurring_decimal.rs @@ -2,29 +2,29 @@ * [166] Fraction to Recurring Decimal * * Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. - * + * * If the fractional part is repeating, enclose the repeating part in parentheses. - * + * * Example 1: - * - * + * + * * Input: numerator = 1, denominator = 2 * Output: "0.5" - * - * + * + * * Example 2: - * - * + * + * * Input: numerator = 2, denominator = 1 * Output: "2" - * + * * Example 3: - * - * + * + * * Input: numerator = 2, denominator = 3 * Output: "0.(6)" - * - * + * + * */ pub struct Solution {} @@ -44,6 +44,5 @@ mod tests { use super::*; #[test] - fn test_166() { - } + fn test_166() {} } diff --git a/src/n0167_two_sum_ii_input_array_is_sorted.rs b/src/n0167_two_sum_ii_input_array_is_sorted.rs index f4f90864..9fd7a483 100644 --- a/src/n0167_two_sum_ii_input_array_is_sorted.rs +++ b/src/n0167_two_sum_ii_input_array_is_sorted.rs @@ -2,23 +2,23 @@ * [167] Two Sum II - Input array is sorted * * Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. - * + * * The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. - * + * * Note: - * - * + * + * * Your returned answers (both index1 and index2) are not zero-based. * You may assume that each input would have exactly one solution and you may not use the same element twice. - * - * + * + * * Example: - * - * + * + * * Input: numbers = [2,7,11,15], target = 9 * Output: [1,2] * Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. - * + * */ pub struct Solution {} @@ -38,7 +38,7 @@ impl Solution { break; } } - return vec![i as i32 + 1, j as i32 + 1] + return vec![i as i32 + 1, j as i32 + 1]; } } @@ -50,6 +50,6 @@ mod tests { #[test] fn test_167() { - assert_eq!(Solution::two_sum(vec![2,7,11,15], 9), vec![1,2]); + assert_eq!(Solution::two_sum(vec![2, 7, 11, 15], 9), vec![1, 2]); } } diff --git a/src/n0168_excel_sheet_column_title.rs b/src/n0168_excel_sheet_column_title.rs index 0d2ca35f..c61f9875 100644 --- a/src/n0168_excel_sheet_column_title.rs +++ b/src/n0168_excel_sheet_column_title.rs @@ -2,40 +2,40 @@ * [168] Excel Sheet Column Title * * Given a positive integer, return its corresponding column title as appear in an Excel sheet. - * + * * For example: - * - * + * + * * 1 -> A * 2 -> B * 3 -> C * ... * 26 -> Z * 27 -> AA - * 28 -> AB + * 28 -> AB * ... - * - * + * + * * Example 1: - * - * + * + * * Input: 1 * Output: "A" - * - * + * + * * Example 2: - * - * + * + * * Input: 28 * Output: "AB" - * - * + * + * * Example 3: - * - * + * + * * Input: 701 * Output: "ZY" - * + * */ pub struct Solution {} @@ -49,7 +49,10 @@ impl Solution { while n > 0 { let mut code = (n % base) as u8; n = n / base; - if code == 0 { n -= 1; code = base as u8; }; + if code == 0 { + n -= 1; + code = base as u8; + }; let alphabetic = (('A' as u8) + (code - 1_u8)) as char; res.push(alphabetic); } diff --git a/src/n0169_majority_element.rs b/src/n0169_majority_element.rs index dddaf659..ccde478f 100644 --- a/src/n0169_majority_element.rs +++ b/src/n0169_majority_element.rs @@ -2,46 +2,46 @@ * [169] Majority Element * * Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. - * + * * You may assume that the array is non-empty and the majority element always exist in the array. - * + * * Example 1: - * - * + * + * * Input: [3,2,3] * Output: 3 - * + * * Example 2: - * - * + * + * * Input: [2,2,1,1,1,2,2] * Output: 2 - * - * + * + * */ pub struct Solution {} // submission codes start here /* - 抄的题解:Boyer-Moore Voting Algorithm - 自己只能想到 HashMap 和排序, 真是太鸡儿菜了... +抄的题解:Boyer-Moore Voting Algorithm +自己只能想到 HashMap 和排序, 真是太鸡儿菜了... - Boyer-Moore Voting Algorithm 的思路是假设当前值为主元素, 碰到当前值则 +1, 非当前值则 -1, 计数器一旦归零, - 就取下一个数为主元素 +Boyer-Moore Voting Algorithm 的思路是假设当前值为主元素, 碰到当前值则 +1, 非当前值则 -1, 计数器一旦归零, +就取下一个数为主元素 - 最后留下的数一定主元素 +最后留下的数一定主元素 - 证明也很简单, 假设我们从第 i 位开始选择了一个数 A, 并且这个数 A 保持到了循环终止, 那么: +证明也很简单, 假设我们从第 i 位开始选择了一个数 A, 并且这个数 A 保持到了循环终止, 那么: - 我们知道, 第 nums[i..n] 中, A 是主元素, nums[0..i] 中, 有一个数 B 出现了一半的次数 +我们知道, 第 nums[i..n] 中, A 是主元素, nums[0..i] 中, 有一个数 B 出现了一半的次数 - 假如 A = B, 那么 A 出现了大于一半的次数, A 一定是主元素 +假如 A = B, 那么 A 出现了大于一半的次数, A 一定是主元素 - 假如 A != B, 且主元素不是 A, 那么 B 包括其他任何数在整个数组中出现的次数一定不到一半(因为 B 包括其他任何数 - 在前半部分**至多**出现一半, 而在后半部分不到一半), 因此不存在主元素, 这与题目给定的"一定存在主元素"矛盾, 因此 - A 一定是主元素 - */ +假如 A != B, 且主元素不是 A, 那么 B 包括其他任何数在整个数组中出现的次数一定不到一半(因为 B 包括其他任何数 +在前半部分**至多**出现一半, 而在后半部分不到一半), 因此不存在主元素, 这与题目给定的"一定存在主元素"矛盾, 因此 +A 一定是主元素 +*/ impl Solution { pub fn majority_element(nums: Vec) -> i32 { @@ -65,6 +65,6 @@ mod tests { #[test] fn test_169() { - assert_eq!(Solution::majority_element(vec![2,2,1,1,1,2,2]), 2); + assert_eq!(Solution::majority_element(vec![2, 2, 1, 1, 1, 2, 2]), 2); } } diff --git a/src/n0171_excel_sheet_column_number.rs b/src/n0171_excel_sheet_column_number.rs index c0e83b88..a6e6838c 100644 --- a/src/n0171_excel_sheet_column_number.rs +++ b/src/n0171_excel_sheet_column_number.rs @@ -2,40 +2,40 @@ * [171] Excel Sheet Column Number * * Given a column title as appear in an Excel sheet, return its corresponding column number. - * + * * For example: - * - * + * + * * A -> 1 * B -> 2 * C -> 3 * ... * Z -> 26 * AA -> 27 - * AB -> 28 + * AB -> 28 * ... - * - * + * + * * Example 1: - * - * + * + * * Input: "A" * Output: 1 - * - * + * + * * Example 2: - * - * + * + * * Input: "AB" * Output: 28 - * - * + * + * * Example 3: - * - * + * + * * Input: "ZY" * Output: 701 - * + * */ pub struct Solution {} @@ -55,6 +55,5 @@ mod tests { use super::*; #[test] - fn test_171() { - } + fn test_171() {} } diff --git a/src/n0172_factorial_trailing_zeroes.rs b/src/n0172_factorial_trailing_zeroes.rs index db8bcf97..0c9f9691 100644 --- a/src/n0172_factorial_trailing_zeroes.rs +++ b/src/n0172_factorial_trailing_zeroes.rs @@ -2,23 +2,23 @@ * [172] Factorial Trailing Zeroes * * Given an integer n, return the number of trailing zeroes in n!. - * + * * Example 1: - * - * + * + * * Input: 3 * Output: 0 * Explanation: 3! = 6, no trailing zero. - * + * * Example 2: - * - * + * + * * Input: 5 * Output: 1 * Explanation: 5! = 120, one trailing zero. - * + * * Note: Your solution should be in logarithmic time complexity. - * + * */ pub struct Solution {} diff --git a/src/n0173_binary_search_tree_iterator.rs b/src/n0173_binary_search_tree_iterator.rs index 638382ea..582e922a 100644 --- a/src/n0173_binary_search_tree_iterator.rs +++ b/src/n0173_binary_search_tree_iterator.rs @@ -2,19 +2,19 @@ * [173] Binary Search Tree Iterator * * Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. - * + * * Calling next() will return the next smallest number in the BST. - * + * * - * - * - * - * + * + * + * + * * Example: - * + * * - * - * + * + * * BSTIterator iterator = new BSTIterator(root); * iterator.next(); // return 3 * iterator.next(); // return 7 @@ -25,39 +25,37 @@ * iterator.hasNext(); // return true * iterator.next(); // return 20 * iterator.hasNext(); // return false - * - * + * + * * - * + * * Note: - * - * + * + * * next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. * You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called. - * - * + * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; -use std::rc::Rc; +use super::util::tree::{to_tree, TreeNode}; use std::cell::RefCell; +use std::rc::Rc; // submission codes start here /* - 非递归中序遍历 - */ +非递归中序遍历 +*/ pub struct BSTIterator { stack: Vec>>, } - -/** +/** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl BSTIterator { - pub fn new(root: Option>>) -> Self { let mut node = root; let mut stack = Vec::new(); @@ -65,11 +63,9 @@ impl BSTIterator { stack.push(inner.clone()); node = node.unwrap().borrow().left.clone(); } - BSTIterator{ - stack: stack, - } + BSTIterator { stack: stack } } - + /** @return the next smallest number */ pub fn next(&mut self) -> i32 { let node = self.stack.pop().unwrap(); @@ -81,7 +77,7 @@ impl BSTIterator { } res } - + /** @return whether we have a next smallest number */ pub fn has_next(&self) -> bool { !self.stack.is_empty() @@ -103,15 +99,15 @@ mod tests { #[test] fn test_173() { - let mut iterator = BSTIterator::new(tree![7,3,15,null,null,9,20]); - assert_eq!(iterator.next(), 3); // return 3 - assert_eq!(iterator.next(), 7); // return 7 + let mut iterator = BSTIterator::new(tree![7, 3, 15, null, null, 9, 20]); + assert_eq!(iterator.next(), 3); // return 3 + assert_eq!(iterator.next(), 7); // return 7 assert_eq!(iterator.has_next(), true); // return true - assert_eq!(iterator.next(), 9); // return 9 + assert_eq!(iterator.next(), 9); // return 9 assert_eq!(iterator.has_next(), true); // return true - assert_eq!(iterator.next(), 15); // return 15 + assert_eq!(iterator.next(), 15); // return 15 assert_eq!(iterator.has_next(), true); // return true - assert_eq!(iterator.next(), 20); // return 20 + assert_eq!(iterator.next(), 20); // return 20 assert_eq!(iterator.has_next(), false); // return false } } diff --git a/src/n0174_dungeon_game.rs b/src/n0174_dungeon_game.rs index 5e4a4864..c1551250 100644 --- a/src/n0174_dungeon_game.rs +++ b/src/n0174_dungeon_game.rs @@ -4,7 +4,7 @@ * * The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess. - * + * * The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. - * + * * Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers). - * + * * In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. - * + * * - * + * * Write a function to determine the knight's minimum initial health so that he is able to rescue the princess. - * + * * For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN. - * + * * * * @@ -44,44 +44,44 @@ * * *
- * + * * - * + * * Note: - * - * + * + * * The knight's health has no upper bound. * Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. - * - * + * + * */ pub struct Solution {} // submission codes start here /* - DP, 即从每个格子出发到达终点所需的最小生命值为 hp[i][j] +DP, 即从每个格子出发到达终点所需的最小生命值为 hp[i][j] - 则显然, hp[M-1][N-1] = min(dungeon[M-1][N-1], 0) + 1; +则显然, hp[M-1][N-1] = min(dungeon[M-1][N-1], 0) + 1; - hp[i][j] = min(min(hp[i+1][j], hp[i][j+1]) - dungeon[i][j], 1); +hp[i][j] = min(min(hp[i+1][j], hp[i][j+1]) - dungeon[i][j], 1); - 倒推到 hp[0][0] 即可 +倒推到 hp[0][0] 即可 - 这里倒推很重要, 因为正推很难 dp(有后效性) +这里倒推很重要, 因为正推很难 dp(有后效性) - 其实可以优化成 O(M+N) 空间复杂度, 从斜对角线往后推就只需要保存一个小数组, 但是下面这样更简明 - */ +其实可以优化成 O(M+N) 空间复杂度, 从斜对角线往后推就只需要保存一个小数组, 但是下面这样更简明 +*/ impl Solution { pub fn calculate_minimum_hp(dungeon: Vec>) -> i32 { let (height, width) = (dungeon.len(), dungeon[0].len()); // Using dummy row to simplify logic - let mut hp = vec![vec![i32::max_value(); width+1]; height+1]; - hp[height][width-1] = 1; - hp[height-1][width] = 1; + let mut hp = vec![vec![i32::max_value(); width + 1]; height + 1]; + hp[height][width - 1] = 1; + hp[height - 1][width] = 1; for i in (0..height).rev() { for j in (0..width).rev() { - hp[i][j] = i32::max(i32::min(hp[i+1][j], hp[i][j+1]) - dungeon[i][j], 1); + hp[i][j] = i32::max(i32::min(hp[i + 1][j], hp[i][j + 1]) - dungeon[i][j], 1); } } hp[0][0] @@ -97,18 +97,16 @@ mod tests { #[test] fn test_174() { assert_eq!( - Solution::calculate_minimum_hp( - vec![ - vec![-2,-3,3], - vec![-5,-10,1], - vec![10,30,-5], - ]), - 7); + Solution::calculate_minimum_hp(vec![ + vec![-2, -3, 3], + vec![-5, -10, 1], + vec![10, 30, -5], + ]), + 7 + ); assert_eq!( - Solution::calculate_minimum_hp( - vec![ - vec![1,-4,5,-99], - vec![2,-2,-2,-1]]), - 3); + Solution::calculate_minimum_hp(vec![vec![1, -4, 5, -99], vec![2, -2, -2, -1]]), + 3 + ); } } diff --git a/src/n0179_largest_number.rs b/src/n0179_largest_number.rs index 4385d85e..349ffc8b 100644 --- a/src/n0179_largest_number.rs +++ b/src/n0179_largest_number.rs @@ -2,22 +2,22 @@ * [179] Largest Number * * Given a list of non negative integers, arrange them such that they form the largest number. - * + * * Example 1: - * - * + * + * * Input: [10,2] * Output: "210" - * + * * Example 2: - * - * + * + * * Input: [3,30,34,5,9] * Output: "9534330" - * - * + * + * * Note: The result may be very large, so you need to return a string instead of an integer. - * + * */ pub struct Solution {} @@ -25,13 +25,17 @@ pub struct Solution {} impl Solution { pub fn largest_number(nums: Vec) -> String { - let mut nums = nums.into_iter().map(|num| {num.to_string()}).collect::>(); - nums.sort_unstable_by(|a, b| { - format!("{}{}", b, a).cmp(&format!("{}{}", a, b)) - }); - if nums[0] == "0" { return "0".to_owned() } + let mut nums = nums + .into_iter() + .map(|num| num.to_string()) + .collect::>(); + nums.sort_unstable_by(|a, b| format!("{}{}", b, a).cmp(&format!("{}{}", a, b))); + if nums[0] == "0" { + return "0".to_owned(); + } nums.iter().fold(String::new(), |mut s, num| { - s.push_str(num); s + s.push_str(num); + s }) } } @@ -44,7 +48,10 @@ mod tests { #[test] fn test_179() { - assert_eq!(Solution::largest_number(vec![3,30,34,5,9]), "9534330".to_owned()); - assert_eq!(Solution::largest_number(vec![121,12]), "12121".to_owned()); + assert_eq!( + Solution::largest_number(vec![3, 30, 34, 5, 9]), + "9534330".to_owned() + ); + assert_eq!(Solution::largest_number(vec![121, 12]), "12121".to_owned()); } } diff --git a/src/n0187_repeated_dna_sequences.rs b/src/n0187_repeated_dna_sequences.rs index 3bc412f0..d16cf948 100644 --- a/src/n0187_repeated_dna_sequences.rs +++ b/src/n0187_repeated_dna_sequences.rs @@ -2,31 +2,31 @@ * [187] Repeated DNA Sequences * * All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. - * + * * Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. - * + * * Example: - * - * + * + * * Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" - * + * * Output: ["AAAAACCCCC", "CCCCCAAAAA"] - * - * + * + * */ pub struct Solution {} // submission codes start here /* - 首先想到直接长度为 10 的 sliding window 滑过去加一个 HashSet +首先想到直接长度为 10 的 sliding window 滑过去加一个 HashSet - 但这种方法在空间上和每次操作的耗时上都比较差, 可以转化为四进制或者二进制编码来考虑 +但这种方法在空间上和每次操作的耗时上都比较差, 可以转化为四进制或者二进制编码来考虑 - A,C,G,T <-> [00, 01, 10, 11] +A,C,G,T <-> [00, 01, 10, 11] - 那就简单很多了, 往后滑动一格不再需要调整整个 substring, 只需要移位, HashSet 也就存个 u32 即可 - */ +那就简单很多了, 往后滑动一格不再需要调整整个 substring, 只需要移位, HashSet 也就存个 u32 即可 +*/ use std::collections::HashSet; impl Solution { pub fn find_repeated_dna_sequences(s: String) -> Vec { @@ -45,7 +45,8 @@ impl Solution { } // skip first 9 chars if count < 9 { - count += 1; continue; + count += 1; + continue; } // mask high 12-bits seq_code &= 0b0000_0000_0000_1111_1111_1111_1111_1111; @@ -54,22 +55,25 @@ impl Solution { } } // bits code to seq string - repeat.iter().map(|&code| { - let mut substr = String::new(); - let mut code = code; - for _ in 0..10 { - // take the first 2 bits each time - substr.push(match code & 0b0000_0000_0000_1100_0000_0000_0000_0000 { - 0b0000_0000_0000_0000_0000_0000_0000_0000 => 'A', - 0b0000_0000_0000_0100_0000_0000_0000_0000 => 'C', - 0b0000_0000_0000_1000_0000_0000_0000_0000 => 'G', - 0b0000_0000_0000_1100_0000_0000_0000_0000 => 'T', - _ => unreachable!(), - }); - code <<= 2; - } - substr - }).collect() + repeat + .iter() + .map(|&code| { + let mut substr = String::new(); + let mut code = code; + for _ in 0..10 { + // take the first 2 bits each time + substr.push(match code & 0b0000_0000_0000_1100_0000_0000_0000_0000 { + 0b0000_0000_0000_0000_0000_0000_0000_0000 => 'A', + 0b0000_0000_0000_0100_0000_0000_0000_0000 => 'C', + 0b0000_0000_0000_1000_0000_0000_0000_0000 => 'G', + 0b0000_0000_0000_1100_0000_0000_0000_0000 => 'T', + _ => unreachable!(), + }); + code <<= 2; + } + substr + }) + .collect() } } diff --git a/src/n0188_best_time_to_buy_and_sell_stock_iv.rs b/src/n0188_best_time_to_buy_and_sell_stock_iv.rs index a70b1f02..af1d9c09 100644 --- a/src/n0188_best_time_to_buy_and_sell_stock_iv.rs +++ b/src/n0188_best_time_to_buy_and_sell_stock_iv.rs @@ -2,72 +2,74 @@ * [188] Best Time to Buy and Sell Stock IV * * Say you have an array for which the i^th element is the price of a given stock on day i. - * + * * Design an algorithm to find the maximum profit. You may complete at most k transactions. - * + * * Note:
* You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). - * + * * Example 1: - * - * + * + * * Input: [2,4,1], k = 2 * Output: 2 * Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. - * - * + * + * * Example 2: - * - * + * + * * Input: [3,2,6,5,0,3], k = 2 * Output: 7 * Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. * Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. - * + * */ pub struct Solution {} // submission codes start here /* - 已经在 #123 里解过了, 为了方便阅读直接把那题的分析拷贝到这里 +已经在 #123 里解过了, 为了方便阅读直接把那题的分析拷贝到这里 - 先考虑只进行 1 次交易的情况, 我们求以 i *为售出点*, 只进行 1 次交易获得的最大利润, 那么: +先考虑只进行 1 次交易的情况, 我们求以 i *为售出点*, 只进行 1 次交易获得的最大利润, 那么: - f[i] = if f[i-1] > 0 { f[i-1] } else { 0 } + prices[i] - prices[i-1] +f[i] = if f[i-1] > 0 { f[i-1] } else { 0 } + prices[i] - prices[i-1] - 这很容易解, 解完之后找出 f 里的最大值即可, 但这不容易推广到 K 次交易的情况, 因为这时 f[i] 不代表到 i *为止*的最大利润, 无法作为单独的交易帮助递推 - (到 i 为止的含义是售出点可以在 [0,i] 之间) +这很容易解, 解完之后找出 f 里的最大值即可, 但这不容易推广到 K 次交易的情况, 因为这时 f[i] 不代表到 i *为止*的最大利润, 无法作为单独的交易帮助递推 +(到 i 为止的含义是售出点可以在 [0,i] 之间) - 我们可以稍作改进, 变成求以 i 为结束点, 只进行 1 次交易获得的最大利润, 那么: +我们可以稍作改进, 变成求以 i 为结束点, 只进行 1 次交易获得的最大利润, 那么: - f[i] = max( - f[i-1], - prices[i] - min(prices[j] { j in [0, i-1] }) - ) +f[i] = max( + f[i-1], + prices[i] - min(prices[j] { j in [0, i-1] }) +) - 这仍然是一个 O(N) 的解法, 因为 min(prices[j] { j in [0, i-1] }) 不需要遍历, 可以在递推过程中直接维护好 +这仍然是一个 O(N) 的解法, 因为 min(prices[j] { j in [0, i-1] }) 不需要遍历, 可以在递推过程中直接维护好 - 现在再推广到进行 K 次交易的情况, 那我们要求以 i 为结束点, 进行 k 次交易获得的最大利润, 这时有了变化, 我们可以在 j 之前再进行 K - 1 次交易: +现在再推广到进行 K 次交易的情况, 那我们要求以 i 为结束点, 进行 k 次交易获得的最大利润, 这时有了变化, 我们可以在 j 之前再进行 K - 1 次交易: - f[k, i] = max( - f[k, i-1], - prices[i] + max(f[k-1, j] - prices[j]) { j in [0, i-1] } ) - ) +f[k, i] = max( + f[k, i-1], + prices[i] + max(f[k-1, j] - prices[j]) { j in [0, i-1] } ) +) - 显然, f[0, i] = 0, f[k, 0] = 0 +显然, f[0, i] = 0, f[k, 0] = 0 - 这个算法可以形象地描述一下, 在 k = 1 时, 我们每次要找的就是 i 之前的最低谷点作为这次交易的开始点 j, 而当 k > 1 时, - 我们 i 之前就有可能已经进行过交易了, 这时我们在找开始点 j 时, 就要同时考虑 "直到 j 为止, k-1 次交易的最大收益" - "j 本身的值". 以此来找到一个最佳点 j +这个算法可以形象地描述一下, 在 k = 1 时, 我们每次要找的就是 i 之前的最低谷点作为这次交易的开始点 j, 而当 k > 1 时, +我们 i 之前就有可能已经进行过交易了, 这时我们在找开始点 j 时, 就要同时考虑 "直到 j 为止, k-1 次交易的最大收益" - "j 本身的值". 以此来找到一个最佳点 j - 在实现时, 假如用 Bottom-Up 递推, 那么只需要维护一个 vec[i], 因为每轮递推时只会考虑上一轮的数据, 我们可以复用这个 O(N) 的额外存储空间 +在实现时, 假如用 Bottom-Up 递推, 那么只需要维护一个 vec[i], 因为每轮递推时只会考虑上一轮的数据, 我们可以复用这个 O(N) 的额外存储空间 - 最后, 这题会给 k 非常大的 corner case, 实际上 k 大于 prices.len() / 2 后面就没有意义了, 可以 shortcut 掉(== 允许无穷次交易的场景), 下面写的比较糙, - 直接限制了一下循环次数, 实际跑的时候运行时间会长一点 - */ +最后, 这题会给 k 非常大的 corner case, 实际上 k 大于 prices.len() / 2 后面就没有意义了, 可以 shortcut 掉(== 允许无穷次交易的场景), 下面写的比较糙, +直接限制了一下循环次数, 实际跑的时候运行时间会长一点 +*/ impl Solution { pub fn max_profit(k: i32, prices: Vec) -> i32 { - if prices.is_empty() { return 0 } + if prices.is_empty() { + return 0; + } let max_trans = k as usize; let mut cache = vec![0; prices.len()]; for _ in 0..usize::min(max_trans, prices.len() / 2 + 1) { @@ -76,12 +78,12 @@ impl Solution { for i in 1..prices.len() { // 复用 vec 前暂存一下前一次的计算结果 let temp = cache[i]; - cache[i] = i32::max(cache[i-1], best_buy_in + prices[i]); + cache[i] = i32::max(cache[i - 1], best_buy_in + prices[i]); // 更新 best_buy_in best_buy_in = i32::max(best_buy_in, temp - prices[i]); } } - return *cache.last().unwrap() + return *cache.last().unwrap(); } } @@ -93,6 +95,6 @@ mod tests { #[test] fn test_188() { - assert_eq!(Solution::max_profit(2, vec![3,2,6,5,0,3]), 7); + assert_eq!(Solution::max_profit(2, vec![3, 2, 6, 5, 0, 3]), 7); } } diff --git a/src/n0189_rotate_array.rs b/src/n0189_rotate_array.rs index 8fb93958..644ce374 100644 --- a/src/n0189_rotate_array.rs +++ b/src/n0189_rotate_array.rs @@ -2,34 +2,34 @@ * [189] Rotate Array * * Given an array, rotate the array to the right by k steps, where k is non-negative. - * + * * Example 1: - * - * + * + * * Input: [1,2,3,4,5,6,7] and k = 3 * Output: [5,6,7,1,2,3,4] * Explanation: * rotate 1 steps to the right: [7,1,2,3,4,5,6] * rotate 2 steps to the right: [6,7,1,2,3,4,5] * rotate 3 steps to the right: [5,6,7,1,2,3,4] - * - * + * + * * Example 2: - * - * + * + * * Input: [-1,-100,3,99] and k = 2 * Output: [3,99,-1,-100] - * Explanation: + * Explanation: * rotate 1 steps to the right: [99,-1,-100,3] * rotate 2 steps to the right: [3,99,-1,-100] - * - * + * + * * Note: - * - * + * + * * Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. * Could you do it in-place with O(1) extra space? - * + * */ pub struct Solution {} @@ -66,11 +66,11 @@ mod tests { #[test] fn test_189() { - let mut nums = vec![1,2,3,4,5,6,7]; + let mut nums = vec![1, 2, 3, 4, 5, 6, 7]; Solution::rotate(&mut nums, 3); - assert_eq!(nums, vec![5,6,7,1,2,3,4]); - let mut nums = vec![1,2,3,4,5,6]; + assert_eq!(nums, vec![5, 6, 7, 1, 2, 3, 4]); + let mut nums = vec![1, 2, 3, 4, 5, 6]; Solution::rotate(&mut nums, 2); - assert_eq!(nums, vec![5,6,1,2,3,4]); + assert_eq!(nums, vec![5, 6, 1, 2, 3, 4]); } } diff --git a/src/n0198_house_robber.rs b/src/n0198_house_robber.rs index e4183b5d..e1257f0c 100644 --- a/src/n0198_house_robber.rs +++ b/src/n0198_house_robber.rs @@ -2,41 +2,41 @@ * [198] House Robber * * You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. - * + * * Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. - * + * * Example 1: - * - * + * + * * Input: [1,2,3,1] * Output: 4 * Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). * Total amount you can rob = 1 + 3 = 4. - * + * * Example 2: - * - * + * + * * Input: [2,7,9,3,1] * Output: 12 * Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). * Total amount you can rob = 2 + 9 + 1 = 12. - * - * + * + * */ pub struct Solution {} // submission codes start here /* - 动态规划, 记抢到第 i 户为止的最大收益为 F[i], 则: +动态规划, 记抢到第 i 户为止的最大收益为 F[i], 则: - i 有两种情况, 抢或不抢, 抢的话则最大收益是 F[i-2] + nums[i], - 不抢则保持和前一次结束的收益一致, 等于 F[i-1], 于是: +i 有两种情况, 抢或不抢, 抢的话则最大收益是 F[i-2] + nums[i], +不抢则保持和前一次结束的收益一致, 等于 F[i-1], 于是: - F[i] = i32::max(nums[i] + F[i-2], F[i-1]) +F[i] = i32::max(nums[i] + F[i-2], F[i-1]) - 观察到 F[i] 只依赖 F[i-1] 和 F[i-2], 可以用常数空间复杂度完成 - */ +观察到 F[i] 只依赖 F[i-1] 和 F[i-2], 可以用常数空间复杂度完成 +*/ impl Solution { pub fn rob(nums: Vec) -> i32 { let mut former_max = 0; @@ -58,8 +58,8 @@ mod tests { #[test] fn test_198() { - assert_eq!(Solution::rob(vec![2,7,9,3,1]), 12); - assert_eq!(Solution::rob(vec![2,7,9,10,1]), 17); - assert_eq!(Solution::rob(vec![2,1,1,2]), 4); + assert_eq!(Solution::rob(vec![2, 7, 9, 3, 1]), 12); + assert_eq!(Solution::rob(vec![2, 7, 9, 10, 1]), 17); + assert_eq!(Solution::rob(vec![2, 1, 1, 2]), 4); } } diff --git a/src/n0199_binary_tree_right_side_view.rs b/src/n0199_binary_tree_right_side_view.rs index 94f210d1..403a3404 100644 --- a/src/n0199_binary_tree_right_side_view.rs +++ b/src/n0199_binary_tree_right_side_view.rs @@ -2,42 +2,43 @@ * [199] Binary Tree Right Side View * * Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. - * + * * Example: - * - * + * + * * Input: [1,2,3,null,5,null,4] * Output: [1, 3, 4] * Explanation: - * + * * 1 <--- * / \ * 2 3 <--- * \ \ * 5 4 <--- - * + * */ pub struct Solution {} -use super::util::tree::{TreeNode, to_tree}; +use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; use std::collections::VecDeque; +use std::rc::Rc; impl Solution { pub fn right_side_view(root: Option>>) -> Vec { - let mut res = Vec::new(); let mut current_level = 0; - if root.is_none() { return res } + if root.is_none() { + return res; + } let mut deq = VecDeque::new(); deq.push_back((0, root.clone())); res.push(root.as_ref().unwrap().borrow().val); while !deq.is_empty() { if let Some((level, Some(node))) = deq.pop_front() { - deq.push_back((level+1, node.borrow().right.clone())); - deq.push_back((level+1, node.borrow().left.clone())); + deq.push_back((level + 1, node.borrow().right.clone())); + deq.push_back((level + 1, node.borrow().left.clone())); if level > current_level { res.push(node.borrow().val); current_level = level; @@ -56,6 +57,9 @@ mod tests { #[test] fn test_199() { - assert_eq!(Solution::right_side_view(tree![1,2,3,null,5,null,4]), vec![1,3,4]); + assert_eq!( + Solution::right_side_view(tree![1, 2, 3, null, 5, null, 4]), + vec![1, 3, 4] + ); } } diff --git a/src/n0200_number_of_islands.rs b/src/n0200_number_of_islands.rs index 86081f5c..b9bcadd2 100644 --- a/src/n0200_number_of_islands.rs +++ b/src/n0200_number_of_islands.rs @@ -2,30 +2,30 @@ * [200] Number of Islands * * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. - * + * * Example 1: - * - * + * + * * Input: * 11110 * 11010 * 11000 * 00000 - * + * * Output: 1 - * - * + * + * * Example 2: - * - * + * + * * Input: * 11000 * 11000 * 00100 * 00011 - * + * * Output: 3 - * + * */ pub struct Solution {} @@ -34,7 +34,9 @@ pub struct Solution {} // Union-Find Set impl Solution { pub fn num_islands(grid: Vec>) -> i32 { - if grid.is_empty() || grid[0].is_empty() { return 0 } + if grid.is_empty() || grid[0].is_empty() { + return 0; + } let (height, width) = (grid.len(), grid[0].len()); let mut parent = vec![vec![(width, height); width]; height]; for i in 0..height { @@ -43,15 +45,15 @@ impl Solution { continue; } parent[i][j] = (i, j); - if i > 0 && grid[i-1][j] == '1' { - Solution::union(&mut parent, (i, j), (i-1, j)); + if i > 0 && grid[i - 1][j] == '1' { + Solution::union(&mut parent, (i, j), (i - 1, j)); } - if j > 0 && grid[i][j-1] == '1' { - Solution::union(&mut parent, (i, j), (i, j-1)); + if j > 0 && grid[i][j - 1] == '1' { + Solution::union(&mut parent, (i, j), (i, j - 1)); } } } - let mut cnt= 0; + let mut cnt = 0; for i in 0..height { for j in 0..width { if parent[i][j] == (i, j) { @@ -81,7 +83,7 @@ impl Solution { let p1 = Solution::get_parent(parent, p1); let p2 = Solution::get_parent(parent, p2); if p1 == p2 { - return + return; } parent[p1.0][p1.1] = p2 } @@ -96,25 +98,21 @@ mod tests { #[test] fn test_200() { assert_eq!( - Solution::num_islands( - vec![ - vec!['1','1','1','1','0',], - vec!['1','1','0','1','0',], - vec!['1','1','0','0','0',], - vec!['0','0','0','0','0',], - ] - ), + Solution::num_islands(vec![ + vec!['1', '1', '1', '1', '0',], + vec!['1', '1', '0', '1', '0',], + vec!['1', '1', '0', '0', '0',], + vec!['0', '0', '0', '0', '0',], + ]), 1 ); assert_eq!( - Solution::num_islands( - vec![ - vec!['1','1','o','1','0',], - vec!['1','1','0','1','0',], - vec!['1','1','0','0','0',], - vec!['0','0','0','1','1',], - ] - ), + Solution::num_islands(vec![ + vec!['1', '1', 'o', '1', '0',], + vec!['1', '1', '0', '1', '0',], + vec!['1', '1', '0', '0', '0',], + vec!['0', '0', '0', '1', '1',], + ]), 3 ); } diff --git a/src/n0201_bitwise_and_of_numbers_range.rs b/src/n0201_bitwise_and_of_numbers_range.rs index d292a442..6fc338b7 100644 --- a/src/n0201_bitwise_and_of_numbers_range.rs +++ b/src/n0201_bitwise_and_of_numbers_range.rs @@ -2,17 +2,17 @@ * [201] Bitwise AND of Numbers Range * * Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. - * + * * Example 1: - * - * + * + * * Input: [5,7] * Output: 4 - * - * + * + * * Example 2: - * - * + * + * * Input: [0,1] * Output: 0 */ @@ -26,13 +26,13 @@ impl Solution { let mut m = m; let mut n = n; if m == 0 { - return 0 + return 0; } let mut step = 1; while m != n { // shortcut if m == 0 { - return 0 + return 0; } m >>= 1; n >>= 1; diff --git a/src/n0202_happy_number.rs b/src/n0202_happy_number.rs index fe62294c..3443f1db 100644 --- a/src/n0202_happy_number.rs +++ b/src/n0202_happy_number.rs @@ -2,20 +2,20 @@ * [202] Happy Number * * Write an algorithm to determine if a number is "happy". - * + * * A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. - * - * Example: - * - * + * + * Example: + * + * * Input: 19 * Output: true - * Explanation: + * Explanation: * 1^2 + 9^2 = 82 * 8^2 + 2^2 = 68 * 6^2 + 8^2 = 100 * 1^2 + 0^2 + 0^2 = 1 - * + * */ pub struct Solution {} @@ -30,14 +30,14 @@ impl Solution { set.insert(n); let temp = Solution::next(n); if temp == 1 { - return true + return true; } if !set.insert(temp) { - return false + return false; } n = temp } - return false + return false; } fn next(n: i32) -> i32 { diff --git a/src/n0203_remove_linked_list_elements.rs b/src/n0203_remove_linked_list_elements.rs index f7611261..290923d6 100644 --- a/src/n0203_remove_linked_list_elements.rs +++ b/src/n0203_remove_linked_list_elements.rs @@ -2,17 +2,17 @@ * [203] Remove Linked List Elements * * Remove all elements from a linked list of integers that have value val. - * + * * Example: - * - * + * + * * Input: 1->2->6->3->4->5->6, val = 6 * Output: 1->2->3->4->5 - * - * + * + * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here @@ -39,6 +39,9 @@ mod tests { #[test] fn test_203() { - assert_eq!(Solution::remove_elements(linked![1,2,6,3,4,5,6], 6), linked![1,2,3,4,5]); + assert_eq!( + Solution::remove_elements(linked![1, 2, 6, 3, 4, 5, 6], 6), + linked![1, 2, 3, 4, 5] + ); } } diff --git a/src/n0204_count_primes.rs b/src/n0204_count_primes.rs index df6d3a7a..4ec5d5c3 100644 --- a/src/n0204_count_primes.rs +++ b/src/n0204_count_primes.rs @@ -2,15 +2,15 @@ * [204] Count Primes * * Count the number of prime numbers less than a non-negative number, n. - * + * * Example: - * - * + * + * * Input: 10 * Output: 4 * Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. - * - * + * + * */ pub struct Solution {} @@ -18,7 +18,9 @@ pub struct Solution {} impl Solution { pub fn count_primes(n: i32) -> i32 { - if n <= 2 { return 0 } + if n <= 2 { + return 0; + } let mut is_prime = vec![true; n as usize]; is_prime[0] = false; is_prime[1] = false; @@ -26,7 +28,7 @@ impl Solution { while i * i < n { if !is_prime[i as usize] { i += 1; - continue + continue; } let mut j = i * i; while j < n { @@ -37,11 +39,12 @@ impl Solution { } let mut count = 0; for &v in is_prime.iter() { - if v { count += 1 } + if v { + count += 1 + } } count } - } // submission codes end diff --git a/src/n0205_isomorphic_strings.rs b/src/n0205_isomorphic_strings.rs index 91730ed2..6bb77373 100644 --- a/src/n0205_isomorphic_strings.rs +++ b/src/n0205_isomorphic_strings.rs @@ -2,41 +2,41 @@ * [205] Isomorphic Strings * * Given two strings s and t, determine if they are isomorphic. - * + * * Two strings are isomorphic if the characters in s can be replaced to get t. - * + * * All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. - * + * * Example 1: - * - * + * + * * Input: s = "egg", t = "add" * Output: true - * - * + * + * * Example 2: - * - * + * + * * Input: s = "foo", t = "bar" * Output: false - * + * * Example 3: - * - * + * + * * Input: s = "paper", t = "title" * Output: true - * + * * Note:
* You may assume both s and t have the same length. - * + * */ pub struct Solution {} // submission codes start here -use std::collections::HashMap; -use std::collections::hash_map::Entry; use std::char; +use std::collections::hash_map::Entry; +use std::collections::HashMap; impl Solution { pub fn is_isomorphic(s: String, t: String) -> bool { Solution::code(s) == Solution::code(t) @@ -47,7 +47,7 @@ impl Solution { let mut start: char = '0'; let mut res = String::new(); for ch in s.chars() { - let v = map.entry(ch).or_insert_with(||{ + let v = map.entry(ch).or_insert_with(|| { start = ((start as u8) + 1) as char; start }); @@ -65,8 +65,17 @@ mod tests { #[test] fn test_205() { - assert_eq!(Solution::is_isomorphic("egg".to_owned(), "app".to_owned()), true); - assert_eq!(Solution::is_isomorphic("pecil".to_owned(), "this".to_owned()), false); - assert_eq!(Solution::is_isomorphic("paper".to_owned(), "title".to_owned()), true); + assert_eq!( + Solution::is_isomorphic("egg".to_owned(), "app".to_owned()), + true + ); + assert_eq!( + Solution::is_isomorphic("pecil".to_owned(), "this".to_owned()), + false + ); + assert_eq!( + Solution::is_isomorphic("paper".to_owned(), "title".to_owned()), + true + ); } } diff --git a/src/n0206_reverse_linked_list.rs b/src/n0206_reverse_linked_list.rs index 9cb97f5a..bdbe34e4 100644 --- a/src/n0206_reverse_linked_list.rs +++ b/src/n0206_reverse_linked_list.rs @@ -16,7 +16,7 @@ * */ pub struct Solution {} -use super::util::linked_list::{ListNode, to_list}; +use super::util::linked_list::{to_list, ListNode}; // submission codes start here @@ -41,6 +41,9 @@ mod tests { #[test] fn test_206() { - assert_eq!(Solution::reverse_list(linked![1,2,3,4,5]), linked![5,4,3,2,1]); + assert_eq!( + Solution::reverse_list(linked![1, 2, 3, 4, 5]), + linked![5, 4, 3, 2, 1] + ); } } diff --git a/src/n0209_minimum_size_subarray_sum.rs b/src/n0209_minimum_size_subarray_sum.rs index ff7ff206..13b02448 100644 --- a/src/n0209_minimum_size_subarray_sum.rs +++ b/src/n0209_minimum_size_subarray_sum.rs @@ -36,12 +36,15 @@ impl Solution { min = i32::min(min, j as i32 - i as i32 + 2); break; } - } } j += 1; } - if found { min } else { 0 } + if found { + min + } else { + 0 + } } } @@ -53,11 +56,7 @@ mod tests { #[test] fn test_209() { - assert_eq!(Solution::min_sub_array_len(7, vec![2,3,1,2,4,3]), 2); - assert_eq!(Solution::min_sub_array_len(4, vec![1,4,4]), 1); + assert_eq!(Solution::min_sub_array_len(7, vec![2, 3, 1, 2, 4, 3]), 2); + assert_eq!(Solution::min_sub_array_len(4, vec![1, 4, 4]), 1); } } - - - - diff --git a/src/n0210_course_schedule_ii.rs b/src/n0210_course_schedule_ii.rs index 4b154595..336fe345 100644 --- a/src/n0210_course_schedule_ii.rs +++ b/src/n0210_course_schedule_ii.rs @@ -70,7 +70,11 @@ impl Solution { } } } - if res.len() == num { res } else { vec![] } + if res.len() == num { + res + } else { + vec![] + } } } @@ -83,6 +87,9 @@ mod tests { #[test] fn test_210() { assert_eq!(Solution::find_order(2, vec![vec![1, 0]]), vec![0, 1]); - assert_eq!(Solution::find_order(4, vec![vec![1, 0], vec![2,0], vec![3,1], vec![3,2]]), vec![0,1,2,3]); + assert_eq!( + Solution::find_order(4, vec![vec![1, 0], vec![2, 0], vec![3, 1], vec![3, 2]]), + vec![0, 1, 2, 3] + ); } } diff --git a/src/n0211_add_and_search_word_data_structure_design.rs b/src/n0211_add_and_search_word_data_structure_design.rs index a2cbff82..fbab7949 100644 --- a/src/n0211_add_and_search_word_data_structure_design.rs +++ b/src/n0211_add_and_search_word_data_structure_design.rs @@ -30,7 +30,6 @@ pub struct Solution {} // submission codes start here - struct WordDictionary { root: Option>, } @@ -124,5 +123,4 @@ mod tests { // assert_eq!(dict.search(".ad".to_owned()), true); // assert_eq!(dict.search("da.".to_owned()), true); } - } diff --git a/src/n0213_house_robber_ii.rs b/src/n0213_house_robber_ii.rs index 495a8d26..6dac950c 100644 --- a/src/n0213_house_robber_ii.rs +++ b/src/n0213_house_robber_ii.rs @@ -36,11 +36,11 @@ impl Solution { let (mut prev, mut curr) = (0, 0); for (k, &num) in nums.iter().enumerate() { if k == 0 && !rob_first { - continue + continue; } // k is last element but not the first element if k != 0 && k == (nums.len() - 1) && rob_first { - continue + continue; } let next = i32::max(prev + num, curr); prev = curr; @@ -60,7 +60,7 @@ mod tests { #[test] fn test_213() { - assert_eq!(Solution::rob(vec![2,3,2]), 3); - assert_eq!(Solution::rob(vec![1,2,3,1]), 4); + assert_eq!(Solution::rob(vec![2, 3, 2]), 3); + assert_eq!(Solution::rob(vec![1, 2, 3, 1]), 4); } } diff --git a/src/n0215_kth_largest_element_in_an_array.rs b/src/n0215_kth_largest_element_in_an_array.rs index 56b2c3ca..3c114990 100644 --- a/src/n0215_kth_largest_element_in_an_array.rs +++ b/src/n0215_kth_largest_element_in_an_array.rs @@ -24,8 +24,8 @@ pub struct Solution {} // submission codes start here -use std::collections::BinaryHeap; use std::cmp::Reverse; +use std::collections::BinaryHeap; impl Solution { pub fn find_kth_largest(nums: Vec, k: i32) -> i32 { let k = k as usize; @@ -50,13 +50,10 @@ mod tests { #[test] fn test_215() { - assert_eq!(Solution::find_kth_largest( - vec![3, 2, 3, 1, 2, 4, 5, 5, 6], + assert_eq!( + Solution::find_kth_largest(vec![3, 2, 3, 1, 2, 4, 5, 5, 6], 4), 4 - ), 4); - assert_eq!(Solution::find_kth_largest( - vec![3,2,1,5,6,4], - 2 - ), 5); + ); + assert_eq!(Solution::find_kth_largest(vec![3, 2, 1, 5, 6, 4], 2), 5); } } diff --git a/src/n0216_combination_sum_iii.rs b/src/n0216_combination_sum_iii.rs index f2342f01..d6f797fa 100644 --- a/src/n0216_combination_sum_iii.rs +++ b/src/n0216_combination_sum_iii.rs @@ -33,12 +33,12 @@ pub struct Solution {} impl Solution { pub fn combination_sum3(k: i32, n: i32) -> Vec> { if k > 9 || k < 1 { - return vec![] + return vec![]; } - let max = (0..k).fold(0, |acc, t| { acc + 9 - t }); - let min = (0..k).fold(0, |acc, t| { acc + t }); + let max = (0..k).fold(0, |acc, t| acc + 9 - t); + let min = (0..k).fold(0, |acc, t| acc + t); if n < min || n > max { - return vec![] + return vec![]; } let mut res = Vec::new(); let mut seed = Vec::new(); @@ -51,9 +51,9 @@ impl Solution { if distance == 0 { res.push(curr); } - return + return; } - for i in (prev+1..=9) { + for i in (prev + 1..=9) { if distance - i < 0 { break; } @@ -72,6 +72,9 @@ mod tests { #[test] fn test_216() { - assert_eq!(Solution::combination_sum3(3, 9), vec![vec![1,2,6],vec![1,3,5], vec![2,3,4]]); + assert_eq!( + Solution::combination_sum3(3, 9), + vec![vec![1, 2, 6], vec![1, 3, 5], vec![2, 3, 4]] + ); } } diff --git a/src/n0217_contains_duplicate.rs b/src/n0217_contains_duplicate.rs index c49f64a1..6e2c906d 100644 --- a/src/n0217_contains_duplicate.rs +++ b/src/n0217_contains_duplicate.rs @@ -30,13 +30,15 @@ pub struct Solution {} impl Solution { pub fn contains_duplicate(nums: Vec) -> bool { - if nums.is_empty() { return false } + if nums.is_empty() { + return false; + } let mut nums = nums; nums.sort_unstable(); let mut prev = nums[0]; for i in 1..nums.len() { if nums[i] == prev { - return true + return true; } prev = nums[i] } @@ -54,7 +56,7 @@ mod tests { fn test_217() { assert_eq!(Solution::contains_duplicate(vec![1]), false); assert_eq!(Solution::contains_duplicate(vec![]), false); - assert_eq!(Solution::contains_duplicate(vec![1,2,3,4]), false); - assert_eq!(Solution::contains_duplicate(vec![1,2,3,1]), true); + assert_eq!(Solution::contains_duplicate(vec![1, 2, 3, 4]), false); + assert_eq!(Solution::contains_duplicate(vec![1, 2, 3, 1]), true); } } diff --git a/src/n0219_contains_duplicate_ii.rs b/src/n0219_contains_duplicate_ii.rs index 5f9a0b1c..c5713adb 100644 --- a/src/n0219_contains_duplicate_ii.rs +++ b/src/n0219_contains_duplicate_ii.rs @@ -46,8 +46,10 @@ impl Solution { return true; } map.insert(num, idx); - }, - None => { map.insert(num, idx); }, + } + None => { + map.insert(num, idx); + } } } false @@ -62,7 +64,13 @@ mod tests { #[test] fn test_219() { - assert_eq!(Solution::contains_nearby_duplicate(vec![1,2,3,1,2,3], 2), false); - assert_eq!(Solution::contains_nearby_duplicate(vec![1,2,3,1,2,3], 3), true); + assert_eq!( + Solution::contains_nearby_duplicate(vec![1, 2, 3, 1, 2, 3], 2), + false + ); + assert_eq!( + Solution::contains_nearby_duplicate(vec![1, 2, 3, 1, 2, 3], 3), + true + ); } } diff --git a/src/n0220_contains_duplicate_iii.rs b/src/n0220_contains_duplicate_iii.rs index d7c60991..a29cb2e5 100644 --- a/src/n0220_contains_duplicate_iii.rs +++ b/src/n0220_contains_duplicate_iii.rs @@ -37,19 +37,27 @@ pub struct Solution {} use std::collections::HashMap; impl Solution { pub fn contains_nearby_almost_duplicate(nums: Vec, k: i32, t: i32) -> bool { - if k < 1 || t < 0 { return false } + if k < 1 || t < 0 { + return false; + } let mut map = HashMap::new(); for i in 0..nums.len() { let remap = nums[i] as i64 - i32::min_value() as i64; let bucket = remap / (t as i64 + 1); println!("{} {}", remap, bucket); if map.contains_key(&bucket) - || map.get(&(bucket-1)).map_or(false, |v| { remap - v <= t as i64}) - || map.get(&(bucket+1)).map_or(false, |v| { v - remap <= t as i64}) { - return true + || map + .get(&(bucket - 1)) + .map_or(false, |v| remap - v <= t as i64) + || map + .get(&(bucket + 1)) + .map_or(false, |v| v - remap <= t as i64) + { + return true; } if i >= k as usize { - let last_bucket = (nums[i - k as usize] as i64 - i32::min_value() as i64) / (t as i64 + 1); + let last_bucket = + (nums[i - k as usize] as i64 - i32::min_value() as i64) / (t as i64 + 1); map.remove(&last_bucket); } map.insert(bucket, remap); @@ -68,6 +76,9 @@ mod tests { fn test_220() { // assert_eq!(Solution::contains_nearby_almost_duplicate(vec![1,5,9,1,5,9], 2, 3), false); // assert_eq!(Solution::contains_nearby_almost_duplicate(vec![1,2,3,1], 3, 0), true); - assert_eq!(Solution::contains_nearby_almost_duplicate(vec![-1,2147483647], 1 ,2147483647), false); + assert_eq!( + Solution::contains_nearby_almost_duplicate(vec![-1, 2147483647], 1, 2147483647), + false + ); } } diff --git a/src/n0221_maximal_square.rs b/src/n0221_maximal_square.rs index 10226731..2fbe5b02 100644 --- a/src/n0221_maximal_square.rs +++ b/src/n0221_maximal_square.rs @@ -21,40 +21,43 @@ pub struct Solution {} // submission codes start here /* - DP, f(i, j) to represent the max square of matrix that end with (i, j) (right bottom corener), then: +DP, f(i, j) to represent the max square of matrix that end with (i, j) (right bottom corener), then: - f(0, 0) = matrix[0][0] - f(i, j) = if matrix[0][0] { min(f(i-1,j), f(i,j-1), f(i-1)(j-1)) + 1 } else { 0 } +f(0, 0) = matrix[0][0] +f(i, j) = if matrix[0][0] { min(f(i-1,j), f(i,j-1), f(i-1)(j-1)) + 1 } else { 0 } - The equation explained: +The equation explained: - matrix: dp: - 1 1 1 1 1 1 - 1 1 1 -> 1 2 2 - 1 1 1 1 2 3 - */ +matrix: dp: +1 1 1 1 1 1 +1 1 1 -> 1 2 2 +1 1 1 1 2 3 +*/ impl Solution { pub fn maximal_square(matrix: Vec>) -> i32 { - if matrix.is_empty() || matrix[0].is_empty() { return 0 } + if matrix.is_empty() || matrix[0].is_empty() { + return 0; + } let (height, width) = (matrix.len(), matrix[0].len()); let mut dp = vec![vec![0; width]; height]; let mut max = 0; for i in 0..height { for j in 0..width { - if matrix[i][j] == '0' { continue } + if matrix[i][j] == '0' { + continue; + } dp[i][j] = i32::min( i32::min( - if i < 1 { 0 } else { dp[i-1][j] }, - if j < 1 { 0 } else { dp[i][j-1] } + if i < 1 { 0 } else { dp[i - 1][j] }, + if j < 1 { 0 } else { dp[i][j - 1] }, ), - if i < 1 || j < 1 { 0 } else { dp[i-1][j-1] } + if i < 1 || j < 1 { 0 } else { dp[i - 1][j - 1] }, ) + 1; max = i32::max(max, dp[i][j]) } } max * max } - } // submission codes end @@ -66,13 +69,13 @@ mod tests { #[test] fn test_221() { assert_eq!( - Solution::maximal_square( - vec![ - vec!['1','0','1','0','0'], - vec!['1','0','1','1','1'], - vec!['1','1','1','1','1'], - vec!['1','0','0','1','0'], - ]), - 4) + Solution::maximal_square(vec![ + vec!['1', '0', '1', '0', '0'], + vec!['1', '0', '1', '1', '1'], + vec!['1', '1', '1', '1', '1'], + vec!['1', '0', '0', '1', '0'], + ]), + 4 + ) } } diff --git a/src/n0222_count_complete_tree_nodes.rs b/src/n0222_count_complete_tree_nodes.rs index df44949b..c511399d 100644 --- a/src/n0222_count_complete_tree_nodes.rs +++ b/src/n0222_count_complete_tree_nodes.rs @@ -26,8 +26,8 @@ use super::util::tree::{to_tree, TreeNode}; // submission codes start here -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn count_nodes(root: Option>>) -> i32 { // 0. get the hight of full nodes @@ -36,10 +36,12 @@ impl Solution { let mut result = 0; while let Some(inner) = curr { height += 1; - result += 2_i32.pow(height-1); + result += 2_i32.pow(height - 1); curr = inner.borrow().right.clone(); } - if height == 0 { return result } + if height == 0 { + return result; + } // 1. 'binary search' to find the node number of the lowest level // the lowest level may have 0~2^H-1 node let mut curr_root = root.clone(); @@ -53,7 +55,7 @@ impl Solution { } if node.unwrap().borrow().right.is_some() { curr_root = curr_root.unwrap().borrow().right.clone(); - result += 2_i32.pow(height-1); + result += 2_i32.pow(height - 1); } else { curr_root = curr_root.unwrap().borrow().left.clone(); } @@ -74,10 +76,10 @@ mod tests { #[test] fn test_222() { - assert_eq!(Solution::count_nodes(tree![1,1,1,1,1,1,1]), 7); + assert_eq!(Solution::count_nodes(tree![1, 1, 1, 1, 1, 1, 1]), 7); assert_eq!(Solution::count_nodes(tree![]), 0); - assert_eq!(Solution::count_nodes(tree![1,1]), 2); + assert_eq!(Solution::count_nodes(tree![1, 1]), 2); assert_eq!(Solution::count_nodes(tree![1]), 1); - assert_eq!(Solution::count_nodes(tree![1,1,1]), 3); + assert_eq!(Solution::count_nodes(tree![1, 1, 1]), 3); } } diff --git a/src/n0223_rectangle_area.rs b/src/n0223_rectangle_area.rs index 1604e8f7..b90235dd 100644 --- a/src/n0223_rectangle_area.rs +++ b/src/n0223_rectangle_area.rs @@ -25,13 +25,19 @@ pub struct Solution {} // mention the integer divition impl Solution { pub fn compute_area(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32, h: i32) -> i32 { - let center1 = ((a+c), (b+d)); - let center2 = ((e+g), (f+h)); - let rect1 = (c-a,d-b); - let rect2 = (g-e,h-f); - let x_intersect = i32::min((rect1.0 + rect2.0 - (center1.0-center2.0).abs()), i32::min(2 * rect1.0, 2 * rect2.0)) / 2; + let center1 = ((a + c), (b + d)); + let center2 = ((e + g), (f + h)); + let rect1 = (c - a, d - b); + let rect2 = (g - e, h - f); + let x_intersect = i32::min( + (rect1.0 + rect2.0 - (center1.0 - center2.0).abs()), + i32::min(2 * rect1.0, 2 * rect2.0), + ) / 2; let x_intersect = if x_intersect < 0 { 0 } else { x_intersect }; - let y_intersect = i32::min((rect1.1 + rect2.1 - (center1.1-center2.1).abs()), i32::min(2 * rect1.1, 2 * rect2.1)) / 2; + let y_intersect = i32::min( + (rect1.1 + rect2.1 - (center1.1 - center2.1).abs()), + i32::min(2 * rect1.1, 2 * rect2.1), + ) / 2; let y_intersect = if y_intersect < 0 { 0 } else { y_intersect }; rect1.0 * rect1.1 - x_intersect * y_intersect + rect2.0 * rect2.1 } diff --git a/src/n0224_basic_calculator.rs b/src/n0224_basic_calculator.rs index bbdb5077..33ed3112 100644 --- a/src/n0224_basic_calculator.rs +++ b/src/n0224_basic_calculator.rs @@ -35,7 +35,7 @@ pub struct Solution {} // submission codes start here -#[derive(PartialEq,Copy,Clone,Debug)] +#[derive(PartialEq, Copy, Clone, Debug)] enum Token { LeftBracket, RightBracket, @@ -63,20 +63,27 @@ impl Solution { in_num = false; } match ch { - '(' => { token_stream.push(Token::LeftBracket); }, - ')' => { token_stream.push(Token::RightBracket); }, - '+' => { token_stream.push(Token::PlusSign); }, - '-' => { token_stream.push(Token::MinusSign); }, - _ => {}, + '(' => { + token_stream.push(Token::LeftBracket); + } + ')' => { + token_stream.push(Token::RightBracket); + } + '+' => { + token_stream.push(Token::PlusSign); + } + '-' => { + token_stream.push(Token::MinusSign); + } + _ => {} }; - }, + } } } if in_num { token_stream.push(Token::Number(num)); } - // parser let mut stack = Vec::new(); let mut iter = token_stream.into_iter(); @@ -95,35 +102,36 @@ impl Solution { match token { Token::LeftBracket => { stack.push(token); - }, + } Token::RightBracket => { if let Token::Number(right_hand) = stack.pop().unwrap() { stack.pop(); pause = true; token = Token::Number(right_hand); } - }, + } Token::PlusSign => { stack.push(token); - }, + } Token::MinusSign => { stack.push(token); - }, + } Token::Number(num) => { if stack.is_empty() || Token::LeftBracket == *stack.last().unwrap() { stack.push(Token::Number(num)); } else { let sign = stack.pop().unwrap(); if let Token::Number(left_hand) = stack.pop().unwrap() { - let res = left_hand + num * if Token::PlusSign == sign { 1 } else { -1 }; + let res = + left_hand + num * if Token::PlusSign == sign { 1 } else { -1 }; stack.push(Token::Number(res)); } } - }, + } } } if let Token::Number(num) = stack.pop().unwrap() { - return num as i32 + return num as i32; } 0 } diff --git a/src/n0225_implement_stack_using_queues.rs b/src/n0225_implement_stack_using_queues.rs index 9d449490..a4ff6a3b 100644 --- a/src/n0225_implement_stack_using_queues.rs +++ b/src/n0225_implement_stack_using_queues.rs @@ -47,7 +47,7 @@ use std::collections::VecDeque; impl MyStack { /** Initialize your data structure here. */ fn new() -> Self { - MyStack{ + MyStack { q1: VecDeque::new(), q2: VecDeque::new(), } @@ -113,8 +113,8 @@ mod tests { stack.push(1); stack.push(2); - assert_eq!(stack.top(), 2); // returns 2 - assert_eq!(stack.pop(), 2); // returns 2 + assert_eq!(stack.top(), 2); // returns 2 + assert_eq!(stack.pop(), 2); // returns 2 assert_eq!(stack.empty(), false); // returns false assert_eq!(stack.pop(), 1); assert_eq!(stack.empty(), true); diff --git a/src/n0226_invert_binary_tree.rs b/src/n0226_invert_binary_tree.rs index c41bda74..29e2a953 100644 --- a/src/n0226_invert_binary_tree.rs +++ b/src/n0226_invert_binary_tree.rs @@ -58,6 +58,9 @@ mod tests { #[test] fn test_226() { - assert_eq!(Solution::invert_tree(tree![4,2,7,1,3,6,9]), tree![4,7,2,9,6,3,1]); + assert_eq!( + Solution::invert_tree(tree![4, 2, 7, 1, 3, 6, 9]), + tree![4, 7, 2, 9, 6, 3, 1] + ); } } diff --git a/src/n0227_basic_calculator_ii.rs b/src/n0227_basic_calculator_ii.rs index 0b91565d..cd52accb 100644 --- a/src/n0227_basic_calculator_ii.rs +++ b/src/n0227_basic_calculator_ii.rs @@ -47,7 +47,9 @@ impl Solution { let mut multiple = true; for ch in s.chars() { match ch { - '0'..='9' => { curr = 10 * curr + (ch as u8 - '0' as u8) as i64; }, + '0'..='9' => { + curr = 10 * curr + (ch as u8 - '0' as u8) as i64; + } '+' | '-' => { if has_prev { if multiple { @@ -58,9 +60,9 @@ impl Solution { has_prev = false; } acc += curr * sign; - curr = 0; - sign = if ch == '+' { 1 } else { -1 }; - } + curr = 0; + sign = if ch == '+' { 1 } else { -1 }; + } '*' | '/' => { if has_prev { if multiple { @@ -73,8 +75,8 @@ impl Solution { prev = curr; curr = 0; multiple = if ch == '*' { true } else { false }; - }, - _ => {}, + } + _ => {} } } if has_prev { @@ -91,7 +93,7 @@ impl Solution { // submission codes end - #[cfg(test)] +#[cfg(test)] mod tests { use super::*; diff --git a/src/n0228_summary_ranges.rs b/src/n0228_summary_ranges.rs index e99dbad2..bb36db17 100644 --- a/src/n0228_summary_ranges.rs +++ b/src/n0228_summary_ranges.rs @@ -26,7 +26,9 @@ pub struct Solution {} impl Solution { pub fn summary_ranges(nums: Vec) -> Vec { - if nums.is_empty() { return vec![] } + if nums.is_empty() { + return vec![]; + } let mut res = Vec::new(); let mut curr = nums[0]; let mut start = nums[0]; @@ -61,6 +63,9 @@ mod tests { #[test] fn test_228() { - assert_eq!(Solution::summary_ranges(vec![0,1,2,3,4,5,6]), vec_string!["0->6"]); + assert_eq!( + Solution::summary_ranges(vec![0, 1, 2, 3, 4, 5, 6]), + vec_string!["0->6"] + ); } } diff --git a/src/n0229_majority_element_ii.rs b/src/n0229_majority_element_ii.rs index 7cbf6951..26baf79e 100644 --- a/src/n0229_majority_element_ii.rs +++ b/src/n0229_majority_element_ii.rs @@ -24,7 +24,9 @@ pub struct Solution {} impl Solution { pub fn majority_element(nums: Vec) -> Vec { - if nums.is_empty() { return vec![] } + if nums.is_empty() { + return vec![]; + } let (mut vote0, mut vote1, mut candidate0, mut candidate1) = (0, 0, -1, -2); for &num in nums.iter() { if num == candidate0 { @@ -67,10 +69,16 @@ mod tests { #[test] fn test_229() { - assert_eq!(Solution::majority_element(vec![1,1,1,2,2,2,3,3,3]), vec![]); - assert_eq!(Solution::majority_element(vec![1,1,1,2,2,3,3,3]), vec![1,3]); + assert_eq!( + Solution::majority_element(vec![1, 1, 1, 2, 2, 2, 3, 3, 3]), + vec![] + ); + assert_eq!( + Solution::majority_element(vec![1, 1, 1, 2, 2, 3, 3, 3]), + vec![1, 3] + ); assert_eq!(Solution::majority_element(vec![1]), vec![1]); - assert_eq!(Solution::majority_element(vec![5,6,6]), vec![6]); - assert_eq!(Solution::majority_element(vec![1,2,3,4]), vec![]); + assert_eq!(Solution::majority_element(vec![5, 6, 6]), vec![6]); + assert_eq!(Solution::majority_element(vec![1, 2, 3, 4]), vec![]); } } diff --git a/src/n0230_kth_smallest_element_in_a_bst.rs b/src/n0230_kth_smallest_element_in_a_bst.rs index c9063617..65de4484 100644 --- a/src/n0230_kth_smallest_element_in_a_bst.rs +++ b/src/n0230_kth_smallest_element_in_a_bst.rs @@ -51,7 +51,7 @@ impl Solution { pub fn helper(root: Option>>, k: i32, res: &mut i32) -> i32 { if k <= 0 { - return 0 + return 0; } if let Some(node) = root { let left = Solution::helper(node.borrow().left.clone(), k, res); @@ -74,8 +74,8 @@ mod tests { #[test] fn test_230() { - assert_eq!(Solution::kth_smallest(tree![3,1,4,null,2], 1), 1); - assert_eq!(Solution::kth_smallest(tree![3,1,4,null,2], 2), 2); - assert_eq!(Solution::kth_smallest(tree![3,1,4,null,2], 3), 3); + assert_eq!(Solution::kth_smallest(tree![3, 1, 4, null, 2], 1), 1); + assert_eq!(Solution::kth_smallest(tree![3, 1, 4, null, 2], 2), 2); + assert_eq!(Solution::kth_smallest(tree![3, 1, 4, null, 2], 3), 3); } } diff --git a/src/n0232_implement_queue_using_stacks.rs b/src/n0232_implement_queue_using_stacks.rs index a142bd1c..d7ff9543 100644 --- a/src/n0232_implement_queue_using_stacks.rs +++ b/src/n0232_implement_queue_using_stacks.rs @@ -46,7 +46,7 @@ struct MyQueue { impl MyQueue { /** Initialize your data structure here. */ fn new() -> Self { - MyQueue{ + MyQueue { vec1: Vec::new(), vec2: Vec::new(), } @@ -100,8 +100,8 @@ mod tests { queue.push(1); queue.push(2); - assert_eq!(queue.peek(), 1); // returns 1 - assert_eq!(queue.pop(), 1); // returns 1 + assert_eq!(queue.peek(), 1); // returns 1 + assert_eq!(queue.pop(), 1); // returns 1 assert_eq!(queue.empty(), false); // returns false } } diff --git a/src/n0238_product_of_array_except_self.rs b/src/n0238_product_of_array_except_self.rs index 294eca4f..7134f2ba 100644 --- a/src/n0238_product_of_array_except_self.rs +++ b/src/n0238_product_of_array_except_self.rs @@ -28,16 +28,18 @@ x 2 3 4 = 24 */ impl Solution { pub fn product_except_self(nums: Vec) -> Vec { - if nums.len() < 2 { return vec![] } + if nums.len() < 2 { + return vec![]; + } let mut res = vec![1; nums.len()]; let mut n = 1; - for i in (0..nums.len()-1).rev() { - n *= nums[i+1]; + for i in (0..nums.len() - 1).rev() { + n *= nums[i + 1]; res[i] = n; } n = 1; for i in 1..nums.len() { - n *= nums[i-1]; + n *= nums[i - 1]; res[i] *= n; } res @@ -52,6 +54,9 @@ mod tests { #[test] fn test_238() { - assert_eq!(Solution::product_except_self(vec![1,2,3,4]), vec![24,12,8,6]); + assert_eq!( + Solution::product_except_self(vec![1, 2, 3, 4]), + vec![24, 12, 8, 6] + ); } } diff --git a/src/n0239_sliding_window_maximum.rs b/src/n0239_sliding_window_maximum.rs index 3685bb53..116218f6 100644 --- a/src/n0239_sliding_window_maximum.rs +++ b/src/n0239_sliding_window_maximum.rs @@ -74,10 +74,19 @@ mod tests { #[test] fn test_239() { - assert_eq!(Solution::max_sliding_window(vec![9,10,9,-7,-4,-8,2,-6], 5), vec![10,10,9,2]); - assert_eq!(Solution::max_sliding_window(vec![1,3,1,2,0,5], 3), vec![3,3,2,5]); - assert_eq!(Solution::max_sliding_window(vec![7,2,4], 2), vec![7, 4]); - assert_eq!(Solution::max_sliding_window(vec![1,-1], 1), vec![1, -1]); - assert_eq!(Solution::max_sliding_window(vec![1,3,-1,-3,5,3,6,7], 3), vec![3,3,5,5,6,7]); + assert_eq!( + Solution::max_sliding_window(vec![9, 10, 9, -7, -4, -8, 2, -6], 5), + vec![10, 10, 9, 2] + ); + assert_eq!( + Solution::max_sliding_window(vec![1, 3, 1, 2, 0, 5], 3), + vec![3, 3, 2, 5] + ); + assert_eq!(Solution::max_sliding_window(vec![7, 2, 4], 2), vec![7, 4]); + assert_eq!(Solution::max_sliding_window(vec![1, -1], 1), vec![1, -1]); + assert_eq!( + Solution::max_sliding_window(vec![1, 3, -1, -3, 5, 3, 6, 7], 3), + vec![3, 3, 5, 5, 6, 7] + ); } } diff --git a/src/n0241_different_ways_to_add_parentheses.rs b/src/n0241_different_ways_to_add_parentheses.rs index 81070d49..cdb5ceaa 100644 --- a/src/n0241_different_ways_to_add_parentheses.rs +++ b/src/n0241_different_ways_to_add_parentheses.rs @@ -35,15 +35,17 @@ impl Solution { } pub fn helper(input: &str) -> Vec { - if input.is_empty() { return vec![] } + if input.is_empty() { + return vec![]; + } if let Ok(digit) = input.parse::() { - return vec![digit] + return vec![digit]; } let mut res: Vec = Vec::new(); for (i, ch) in input.chars().enumerate() { if ch == '+' || ch == '-' || ch == '*' { let left = Solution::helper(&input[..i]); - let right = Solution::helper(&input[i+1..]); + let right = Solution::helper(&input[i + 1..]); for &a in left.iter() { for &b in right.iter() { res.push(match ch { @@ -68,6 +70,9 @@ mod tests { #[test] fn test_241() { - assert_eq!(Solution::diff_ways_to_compute("2*3-4*5".to_owned()), vec![-34, -10, -14, -10, 10]); + assert_eq!( + Solution::diff_ways_to_compute("2*3-4*5".to_owned()), + vec![-34, -10, -14, -10, 10] + ); } } diff --git a/src/n0242_valid_anagram.rs b/src/n0242_valid_anagram.rs index 12405169..8c809549 100644 --- a/src/n0242_valid_anagram.rs +++ b/src/n0242_valid_anagram.rs @@ -34,7 +34,7 @@ impl Solution { } fn hit(s: String) -> Vec { - let mut hit = vec![0;27]; + let mut hit = vec![0; 27]; for ch in s.chars() { hit[(ch as u8 - 'a' as u8) as usize] += 1; } @@ -50,6 +50,9 @@ mod tests { #[test] fn test_242() { - assert_eq!(Solution::is_anagram("anagram".to_owned(), "nagaram".to_owned()), true); + assert_eq!( + Solution::is_anagram("anagram".to_owned(), "nagaram".to_owned()), + true + ); } } diff --git a/src/n0257_binary_tree_paths.rs b/src/n0257_binary_tree_paths.rs index 3ecde0cb..ef5254c9 100644 --- a/src/n0257_binary_tree_paths.rs +++ b/src/n0257_binary_tree_paths.rs @@ -74,6 +74,9 @@ mod tests { #[test] fn test_257() { - assert_eq!(Solution::binary_tree_paths(tree![1,2,3,null,5]), vec_string!["1->2->5", "1->3"]); + assert_eq!( + Solution::binary_tree_paths(tree![1, 2, 3, null, 5]), + vec_string!["1->2->5", "1->3"] + ); } } diff --git a/src/n0260_single_number_iii.rs b/src/n0260_single_number_iii.rs index d7a0f431..2735cb7d 100644 --- a/src/n0260_single_number_iii.rs +++ b/src/n0260_single_number_iii.rs @@ -48,7 +48,7 @@ mod tests { #[test] fn test_260() { - assert_eq!(Solution::single_number(vec![1,2,1,2,3,4]), vec![3,4]); - assert_eq!(Solution::single_number(vec![1,2,1,3,2,5]), vec![3,5]); + assert_eq!(Solution::single_number(vec![1, 2, 1, 2, 3, 4]), vec![3, 4]); + assert_eq!(Solution::single_number(vec![1, 2, 1, 3, 2, 5]), vec![3, 5]); } } diff --git a/src/n0263_ugly_number.rs b/src/n0263_ugly_number.rs index c519d5f8..1ad0a3cc 100644 --- a/src/n0263_ugly_number.rs +++ b/src/n0263_ugly_number.rs @@ -46,11 +46,11 @@ impl Solution { } else if num == 1 { true } else if num % 5 == 0 { - Solution::is_ugly(num/5) + Solution::is_ugly(num / 5) } else if num % 3 == 0 { - Solution::is_ugly(num/3) + Solution::is_ugly(num / 3) } else if num % 2 == 0 { - Solution::is_ugly(num/2) + Solution::is_ugly(num / 2) } else { false } diff --git a/src/n0264_ugly_number_ii.rs b/src/n0264_ugly_number_ii.rs index 428c4e80..48be94d1 100644 --- a/src/n0264_ugly_number_ii.rs +++ b/src/n0264_ugly_number_ii.rs @@ -28,15 +28,21 @@ impl Solution { let mut base2 = 0; let mut base3 = 0; let mut base5 = 0; - let mut ugly = vec![1;1]; + let mut ugly = vec![1; 1]; for _ in 1..n { let next2 = ugly[base2] * 2; let next3 = ugly[base3] * 3; let next5 = ugly[base5] * 5; let next = i32::min(next2, i32::min(next3, next5)); - if next2 == next { base2 += 1 } - if next3 == next { base3 += 1 } - if next5 == next { base5 += 1 } + if next2 == next { + base2 += 1 + } + if next3 == next { + base3 += 1 + } + if next5 == next { + base5 += 1 + } ugly.push(next) } *ugly.last().unwrap() diff --git a/src/n0268_missing_number.rs b/src/n0268_missing_number.rs index ce7ca3d5..c8636b99 100644 --- a/src/n0268_missing_number.rs +++ b/src/n0268_missing_number.rs @@ -26,7 +26,7 @@ pub struct Solution {} impl Solution { pub fn missing_number(nums: Vec) -> i32 { - ((nums.len() + 1) * nums.len()) as i32 / 2 - nums.into_iter().fold(0, |acc, v| { acc + v }) + ((nums.len() + 1) * nums.len()) as i32 / 2 - nums.into_iter().fold(0, |acc, v| acc + v) } } @@ -38,6 +38,6 @@ mod tests { #[test] fn test_268() { - assert_eq!(Solution::missing_number(vec![3,0,1]), 2); + assert_eq!(Solution::missing_number(vec![3, 0, 1]), 2); } } diff --git a/src/n0274_h_index.rs b/src/n0274_h_index.rs index 9e4aea5c..936ba1e7 100644 --- a/src/n0274_h_index.rs +++ b/src/n0274_h_index.rs @@ -45,6 +45,6 @@ mod tests { #[test] fn test_274() { - assert_eq!(Solution::h_index(vec![3,0,6,1,5]), 3); + assert_eq!(Solution::h_index(vec![3, 0, 6, 1, 5]), 3); } } diff --git a/src/n0275_h_index_ii.rs b/src/n0275_h_index_ii.rs index 7ac39a0f..63e21671 100644 --- a/src/n0275_h_index_ii.rs +++ b/src/n0275_h_index_ii.rs @@ -33,13 +33,17 @@ pub struct Solution {} impl Solution { pub fn h_index(citations: Vec) -> i32 { - if citations.is_empty() { return 0 } + if citations.is_empty() { + return 0; + } let len = citations.len(); let (mut low, mut high) = (0_usize, len - 1); while low <= high { let mid = low + (high - low) / 2; if citations[mid] >= (len - mid) as i32 { - if mid == 0 { break } + if mid == 0 { + break; + } high = mid - 1; } else { low = mid + 1; @@ -61,7 +65,7 @@ mod tests { assert_eq!(Solution::h_index(vec![0]), 0); assert_eq!(Solution::h_index(vec![11, 15]), 2); assert_eq!(Solution::h_index(vec![1]), 1); - assert_eq!(Solution::h_index(vec![0,1,3,5,6]), 3); - assert_eq!(Solution::h_index(vec![0,4,4,5,6]), 4); + assert_eq!(Solution::h_index(vec![0, 1, 3, 5, 6]), 3); + assert_eq!(Solution::h_index(vec![0, 4, 4, 5, 6]), 4); } } diff --git a/src/n0279_perfect_squares.rs b/src/n0279_perfect_squares.rs index 60419c54..349d9584 100644 --- a/src/n0279_perfect_squares.rs +++ b/src/n0279_perfect_squares.rs @@ -25,14 +25,16 @@ pub struct Solution {} use std::collections::VecDeque; impl Solution { pub fn num_squares(n: i32) -> i32 { - if n < 1 { return 0 } + if n < 1 { + return 0; + } let mut deq = VecDeque::new(); - deq.push_back((1,n)); + deq.push_back((1, n)); while let Some((level, num)) = deq.pop_front() { let mut base = 1; while base * base <= num { if base * base == num { - return level + return level; } deq.push_back((level + 1, num - base * base)); base += 1; diff --git a/src/n0283_move_zeroes.rs b/src/n0283_move_zeroes.rs index e5949435..1087acab 100644 --- a/src/n0283_move_zeroes.rs +++ b/src/n0283_move_zeroes.rs @@ -40,8 +40,8 @@ mod tests { #[test] fn test_283() { - let mut vec = vec![0,1,0,3,12]; + let mut vec = vec![0, 1, 0, 3, 12]; Solution::move_zeroes(&mut vec); - assert_eq!(vec, vec![1,3,12,0,0]); + assert_eq!(vec, vec![1, 3, 12, 0, 0]); } } diff --git a/src/n0287_find_the_duplicate_number.rs b/src/n0287_find_the_duplicate_number.rs index b6dfe573..d0111840 100644 --- a/src/n0287_find_the_duplicate_number.rs +++ b/src/n0287_find_the_duplicate_number.rs @@ -63,9 +63,9 @@ mod tests { #[test] fn test_287() { - assert_eq!(Solution::find_duplicate(vec![1,3,4,2,2]), 2); - assert_eq!(Solution::find_duplicate(vec![3,1,3,4,2]), 3); - assert_eq!(Solution::find_duplicate(vec![1,2,3,4,5,5]), 5); - assert_eq!(Solution::find_duplicate(vec![5,1,2,3,4,5]), 5); + assert_eq!(Solution::find_duplicate(vec![1, 3, 4, 2, 2]), 2); + assert_eq!(Solution::find_duplicate(vec![3, 1, 3, 4, 2]), 3); + assert_eq!(Solution::find_duplicate(vec![1, 2, 3, 4, 5, 5]), 5); + assert_eq!(Solution::find_duplicate(vec![5, 1, 2, 3, 4, 5]), 5); } } diff --git a/src/n0289_game_of_life.rs b/src/n0289_game_of_life.rs index 26c84113..37e81fc3 100644 --- a/src/n0289_game_of_life.rs +++ b/src/n0289_game_of_life.rs @@ -49,16 +49,26 @@ pub struct Solution {} impl Solution { pub fn game_of_life(board: &mut Vec>) { let (height, width) = (board.len(), board[0].len()); - let neighbors = vec![(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]; + let neighbors = vec![ + (-1, -1), + (-1, 0), + (-1, 1), + (0, -1), + (0, 1), + (1, -1), + (1, 0), + (1, 1), + ]; for i in 0..height { for j in 0..width { let mut live = 0; for offset in neighbors.iter() { - if (offset.0 < 0 && i == 0) || - (offset.0 > 0 && i == height -1) || - (offset.1 < 0 && j == 0) || - (offset.1 > 0 && j == width -1) { - continue + if (offset.0 < 0 && i == 0) + || (offset.0 > 0 && i == height - 1) + || (offset.1 < 0 && j == 0) + || (offset.1 > 0 && j == width - 1) + { + continue; } let v = board[(i as i32 + offset.0) as usize][(j as i32 + offset.1) as usize]; if v == 1 || v == 3 { @@ -95,18 +105,11 @@ mod tests { #[test] fn test_289() { - let mut test = vec![ - vec![0,1,0], - vec![0,0,1], - vec![1,1,1], - vec![0,0,0], - ]; + let mut test = vec![vec![0, 1, 0], vec![0, 0, 1], vec![1, 1, 1], vec![0, 0, 0]]; Solution::game_of_life(&mut test); - assert_eq!(test, vec![ - vec![0,0,0], - vec![1,0,1], - vec![0,1,1], - vec![0,1,0], - ]); + assert_eq!( + test, + vec![vec![0, 0, 0], vec![1, 0, 1], vec![0, 1, 1], vec![0, 1, 0],] + ); } } diff --git a/src/n0290_word_pattern.rs b/src/n0290_word_pattern.rs index 0258a3f1..adb5cb0e 100644 --- a/src/n0290_word_pattern.rs +++ b/src/n0290_word_pattern.rs @@ -47,11 +47,10 @@ impl Solution { loop { match (s_iter.next(), p_iter.next()) { (Some(sub), Some(ch)) => { - if *p2s.entry(ch).or_insert(sub) != sub || - *s2p.entry(sub).or_insert(ch) != ch { - return false + if *p2s.entry(ch).or_insert(sub) != sub || *s2p.entry(sub).or_insert(ch) != ch { + return false; } - }, + } (None, None) => break, _ => return false, } @@ -68,8 +67,17 @@ mod tests { #[test] fn test_290() { - assert_eq!(Solution::word_pattern("abba".to_owned(), "dog cat cat dog".to_owned()), true); - assert_eq!(Solution::word_pattern("aaaa".to_owned(), "dog cat cat dog".to_owned()), false); - assert_eq!(Solution::word_pattern("abba".to_owned(), "dog cat cat fish".to_owned()), false); + assert_eq!( + Solution::word_pattern("abba".to_owned(), "dog cat cat dog".to_owned()), + true + ); + assert_eq!( + Solution::word_pattern("aaaa".to_owned(), "dog cat cat dog".to_owned()), + false + ); + assert_eq!( + Solution::word_pattern("abba".to_owned(), "dog cat cat fish".to_owned()), + false + ); } } diff --git a/src/n0295_find_median_from_data_stream.rs b/src/n0295_find_median_from_data_stream.rs index c5fd307f..f400c5b0 100644 --- a/src/n0295_find_median_from_data_stream.rs +++ b/src/n0295_find_median_from_data_stream.rs @@ -41,11 +41,11 @@ pub struct Solution {} // submission codes start here -use std::collections::BinaryHeap; use std::cmp::Ordering; +use std::collections::BinaryHeap; #[derive(Eq, PartialEq)] struct Invert { - value: i32 + value: i32, } impl Ord for Invert { @@ -73,7 +73,7 @@ struct MedianFinder { impl MedianFinder { /** initialize your data structure here. */ fn new() -> Self { - MedianFinder{ + MedianFinder { head: BinaryHeap::new(), tail: BinaryHeap::new(), count: 0, @@ -83,7 +83,7 @@ impl MedianFinder { fn add_num(&mut self, num: i32) { self.count += 1; if self.head.is_empty() || num > self.head.peek().unwrap().value { - self.head.push(Invert{value: num}); + self.head.push(Invert { value: num }); } else { self.tail.push(num); } @@ -91,7 +91,9 @@ impl MedianFinder { if self.head.len() > self.tail.len() + 1 { self.tail.push(self.head.pop().unwrap().value); } else if self.head.len() + 1 < self.tail.len() { - self.head.push(Invert{value:self.tail.pop().unwrap()}); + self.head.push(Invert { + value: self.tail.pop().unwrap(), + }); } } diff --git a/src/n0299_bulls_and_cows.rs b/src/n0299_bulls_and_cows.rs index 1ac73e5c..3ef77009 100644 --- a/src/n0299_bulls_and_cows.rs +++ b/src/n0299_bulls_and_cows.rs @@ -65,7 +65,13 @@ mod tests { #[test] fn test_299() { - assert_eq!(Solution::get_hint("1807".to_owned(), "7810".to_owned()), "1A3B".to_owned()); - assert_eq!(Solution::get_hint("1123".to_owned(), "0111".to_owned()), "1A1B".to_owned()); + assert_eq!( + Solution::get_hint("1807".to_owned(), "7810".to_owned()), + "1A3B".to_owned() + ); + assert_eq!( + Solution::get_hint("1123".to_owned(), "0111".to_owned()), + "1A1B".to_owned() + ); } } diff --git a/src/n0300_longest_increasing_subsequence.rs b/src/n0300_longest_increasing_subsequence.rs index d5106299..cf5eee05 100644 --- a/src/n0300_longest_increasing_subsequence.rs +++ b/src/n0300_longest_increasing_subsequence.rs @@ -49,6 +49,6 @@ mod tests { #[test] fn test_300() { - assert_eq!(Solution::length_of_lis(vec![10,9,2,5,3,7,101,18]), 4); + assert_eq!(Solution::length_of_lis(vec![10, 9, 2, 5, 3, 7, 101, 18]), 4); } } diff --git a/src/n0301_remove_invalid_parentheses.rs b/src/n0301_remove_invalid_parentheses.rs index 50f8140e..6d6f2f51 100644 --- a/src/n0301_remove_invalid_parentheses.rs +++ b/src/n0301_remove_invalid_parentheses.rs @@ -56,30 +56,54 @@ impl Solution { res.into_iter().collect() } - fn helper(chs: &Vec, idx: usize, left: i32, l_remain: i32, r_remain: i32, exp: &mut Vec, res: &mut HashSet) { + fn helper( + chs: &Vec, + idx: usize, + left: i32, + l_remain: i32, + r_remain: i32, + exp: &mut Vec, + res: &mut HashSet, + ) { if idx >= chs.len() { if left == 0 { res.insert(exp.iter().collect()); } - return + return; } if chs[idx] == '(' { if l_remain > 0 { - Solution::helper(chs, idx+1, left, l_remain-1, r_remain, &mut exp.clone(), res); + Solution::helper( + chs, + idx + 1, + left, + l_remain - 1, + r_remain, + &mut exp.clone(), + res, + ); } exp.push('('); - Solution::helper(chs, idx+1, left+1, l_remain, r_remain, exp, res); + Solution::helper(chs, idx + 1, left + 1, l_remain, r_remain, exp, res); } else if chs[idx] == ')' { if r_remain > 0 { - Solution::helper(chs, idx+1, left, l_remain, r_remain-1, &mut exp.clone(), res); + Solution::helper( + chs, + idx + 1, + left, + l_remain, + r_remain - 1, + &mut exp.clone(), + res, + ); } if left > 0 { exp.push(')'); - Solution::helper(chs, idx+1, left-1, l_remain, r_remain, exp, res); + Solution::helper(chs, idx + 1, left - 1, l_remain, r_remain, exp, res); } } else { exp.push(chs[idx]); - Solution::helper(chs, idx+1, left, l_remain, r_remain, exp, res); + Solution::helper(chs, idx + 1, left, l_remain, r_remain, exp, res); } } } @@ -92,7 +116,13 @@ mod tests { #[test] fn test_301() { - assert_eq!(Solution::remove_invalid_parentheses("()())()".to_owned()), vec_string!["(())()", "()()()"]); - assert_eq!(Solution::remove_invalid_parentheses("(a)())()".to_owned()), vec_string!["(a)()()", "(a())()"]); + assert_eq!( + Solution::remove_invalid_parentheses("()())()".to_owned()), + vec_string!["(())()", "()()()"] + ); + assert_eq!( + Solution::remove_invalid_parentheses("(a)())()".to_owned()), + vec_string!["(a)()()", "(a())()"] + ); } } diff --git a/src/n0303_range_sum_query_immutable.rs b/src/n0303_range_sum_query_immutable.rs index 04c4aad3..0143a4ab 100644 --- a/src/n0303_range_sum_query_immutable.rs +++ b/src/n0303_range_sum_query_immutable.rs @@ -40,12 +40,12 @@ impl NumArray { res += num; vec.push(res); } - NumArray{nums: vec} + NumArray { nums: vec } } fn sum_range(&self, i: i32, j: i32) -> i32 { let (i, j) = (i as usize, j as usize); - self.nums[j] - if i > 0 { self.nums[i-1] } else { 0 } + self.nums[j] - if i > 0 { self.nums[i - 1] } else { 0 } } } diff --git a/src/n0304_range_sum_query_2d_immutable.rs b/src/n0304_range_sum_query_2d_immutable.rs index 6bb940f6..d9775add 100644 --- a/src/n0304_range_sum_query_2d_immutable.rs +++ b/src/n0304_range_sum_query_2d_immutable.rs @@ -37,7 +37,7 @@ pub struct Solution {} // submission codes start here struct NumMatrix { - cache: Vec> + cache: Vec>, } /** region[2, 2, 3, 4] = @@ -51,27 +51,45 @@ struct NumMatrix { impl NumMatrix { fn new(matrix: Vec>) -> Self { if matrix.is_empty() || matrix[0].is_empty() { - return NumMatrix{cache: vec![vec![]]} + return NumMatrix { + cache: vec![vec![]], + }; } let (x_max, y_max) = (matrix.len(), matrix[0].len()); let mut cache = vec![vec![0; y_max]; x_max]; for x in 0..x_max { for y in 0..y_max { - cache[x][y] = matrix[x][y] + - if y > 0 { cache[x][y-1] } else { 0 } + - if x > 0 { cache[x-1][y] } else { 0 } - - if x > 0 && y > 0 { cache[x-1][y-1] } else { 0 } + cache[x][y] = matrix[x][y] + + if y > 0 { cache[x][y - 1] } else { 0 } + + if x > 0 { cache[x - 1][y] } else { 0 } + - if x > 0 && y > 0 { + cache[x - 1][y - 1] + } else { + 0 + } } } - NumMatrix{cache: cache} + NumMatrix { cache: cache } } fn sum_region(&self, row1: i32, col1: i32, row2: i32, col2: i32) -> i32 { - let (row1,col1,row2,col2) = (row1 as usize, col1 as usize, row2 as usize, col2 as usize); - self.cache[row2][col2] - - if row1 > 0 { self.cache[row1-1][col2] } else { 0 } - - if col1 > 0 { self.cache[row2][col1-1] } else { 0 } + - if row1 > 0 && col1 > 0 { self.cache[row1-1][col1-1]} else { 0 } + let (row1, col1, row2, col2) = (row1 as usize, col1 as usize, row2 as usize, col2 as usize); + self.cache[row2][col2] + - if row1 > 0 { + self.cache[row1 - 1][col2] + } else { + 0 + } + - if col1 > 0 { + self.cache[row2][col1 - 1] + } else { + 0 + } + + if row1 > 0 && col1 > 0 { + self.cache[row1 - 1][col1 - 1] + } else { + 0 + } } } @@ -89,15 +107,13 @@ mod tests { #[test] fn test_304() { - let matrix = NumMatrix::new( - vec![ - vec![3, 0, 1, 4, 2], - vec![5, 6, 3, 2, 1], - vec![1, 2, 0, 1, 5], - vec![4, 1, 0, 1, 7], - vec![1, 0, 3, 0, 5] - ] - ); + let matrix = NumMatrix::new(vec![ + vec![3, 0, 1, 4, 2], + vec![5, 6, 3, 2, 1], + vec![1, 2, 0, 1, 5], + vec![4, 1, 0, 1, 7], + vec![1, 0, 3, 0, 5], + ]); assert_eq!(matrix.sum_region(1, 1, 2, 2), 11); assert_eq!(matrix.sum_region(2, 1, 4, 3), 8); assert_eq!(matrix.sum_region(1, 2, 2, 4), 12); diff --git a/src/n0306_additive_number.rs b/src/n0306_additive_number.rs index 70d8ab37..08b926f4 100644 --- a/src/n0306_additive_number.rs +++ b/src/n0306_additive_number.rs @@ -38,17 +38,17 @@ pub struct Solution {} // 1 99 100 199 impl Solution { pub fn is_additive_number(num: String) -> bool { - let mut chs: Vec = num.chars().map(|c| c.to_digit(10).unwrap() ).collect(); + let mut chs: Vec = num.chars().map(|c| c.to_digit(10).unwrap()).collect(); let mut num1 = 0; let len = chs.len(); // first cut for i in 0..(len / 2 + 1) { num1 = num1 * 10 + chs[i]; - if Solution::second_cut(i+1, len, num1, &chs) { - return true + if Solution::second_cut(i + 1, len, num1, &chs) { + return true; } if num1 == 0 { - break + break; } } false @@ -58,29 +58,36 @@ impl Solution { let mut num2 = 0; for i in from..len { num2 = num2 * 10 + chs[i]; - if Solution::third_cut(i+1, len, num1, num2, chs, false) { - return true + if Solution::third_cut(i + 1, len, num1, num2, chs, false) { + return true; } if num2 == 0 { - break + break; } } false } - fn third_cut(from: usize, len: usize, num1: u32, num2: u32, chs: &Vec, found: bool) -> bool { + fn third_cut( + from: usize, + len: usize, + num1: u32, + num2: u32, + chs: &Vec, + found: bool, + ) -> bool { if found && from >= len { - return true + return true; } let mut num3 = 0; for i in from..len { num3 = num3 * 10 + chs[i]; if num3 == num2 + num1 { - if Solution::third_cut(i+1, len, num2, num3, chs, true) { - return true + if Solution::third_cut(i + 1, len, num2, num3, chs, true) { + return true; } } else if num3 == 0 || num3 > num1 + num2 { - break + break; } } false diff --git a/src/n0307_range_sum_query_mutable.rs b/src/n0307_range_sum_query_mutable.rs index 19a9dc5b..74ec6139 100644 --- a/src/n0307_range_sum_query_mutable.rs +++ b/src/n0307_range_sum_query_mutable.rs @@ -50,19 +50,19 @@ struct NumArray { impl NumArray { fn new(nums: Vec) -> Self { let n = nums.len(); - let mut tree = vec![0; 4*n]; + let mut tree = vec![0; 4 * n]; if n > 0 { - NumArray::build(1, 0, n-1, &mut tree, &nums); + NumArray::build(1, 0, n - 1, &mut tree, &nums); } - NumArray{tree: tree, n: n} + NumArray { tree: tree, n: n } } fn update(&mut self, i: i32, val: i32) { - NumArray::update_internal(i as usize, val, 1, 0, self.n-1, &mut self.tree); + NumArray::update_internal(i as usize, val, 1, 0, self.n - 1, &mut self.tree); } fn sum_range(&self, i: i32, j: i32) -> i32 { - NumArray::sum(1, 0, self.n-1, i as usize, j as usize, &self.tree) + NumArray::sum(1, 0, self.n - 1, i as usize, j as usize, &self.tree) } fn build(node: usize, start: usize, end: usize, tree: &mut Vec, nums: &Vec) { @@ -70,27 +70,41 @@ impl NumArray { tree[node] = nums[start]; } else { let mid = (start + end) / 2; - NumArray::build(2*node, start, mid, tree, nums); - NumArray::build(2*node+1, mid+1, end, tree, nums); - tree[node] = tree[2*node] + tree[2*node+1]; + NumArray::build(2 * node, start, mid, tree, nums); + NumArray::build(2 * node + 1, mid + 1, end, tree, nums); + tree[node] = tree[2 * node] + tree[2 * node + 1]; } } - fn update_internal(i: usize, val: i32, node: usize, start: usize, end: usize, tree: &mut Vec) { + fn update_internal( + i: usize, + val: i32, + node: usize, + start: usize, + end: usize, + tree: &mut Vec, + ) { if start == end { tree[node] = val; } else { let mid = (start + end) / 2; if i <= mid { - NumArray::update_internal(i, val, 2*node, start, mid, tree); + NumArray::update_internal(i, val, 2 * node, start, mid, tree); } else { - NumArray::update_internal(i, val, 2*node+1, mid+1, end, tree); + NumArray::update_internal(i, val, 2 * node + 1, mid + 1, end, tree); } - tree[node] = tree[2*node] + tree[2*node+1]; + tree[node] = tree[2 * node] + tree[2 * node + 1]; } } - fn sum(node: usize, start: usize, end: usize, left: usize, right: usize, tree: &Vec) -> i32 { + fn sum( + node: usize, + start: usize, + end: usize, + left: usize, + right: usize, + tree: &Vec, + ) -> i32 { if right < start || left > end { // not in range 0 @@ -100,8 +114,8 @@ impl NumArray { } else { // partially in range let mid = (start + end) / 2; - NumArray::sum(2*node, start, mid, left, right, tree) + - NumArray::sum(2*node+1, mid+1, end, left, right ,tree) + NumArray::sum(2 * node, start, mid, left, right, tree) + + NumArray::sum(2 * node + 1, mid + 1, end, left, right, tree) } } } @@ -122,7 +136,7 @@ mod tests { #[test] fn test_307() { let _empty = NumArray::new(vec![]); - let mut tree = NumArray::new(vec![1,1,1,1,1,1,1,1,1,1]); + let mut tree = NumArray::new(vec![1, 1, 1, 1, 1, 1, 1, 1, 1, 1]); assert_eq!(tree.sum_range(0, 6), 7); tree.update(0, 2); assert_eq!(tree.sum_range(0, 6), 8); diff --git a/src/n0309_best_time_to_buy_and_sell_stock_with_cooldown.rs b/src/n0309_best_time_to_buy_and_sell_stock_with_cooldown.rs index cf86db2a..0f3f2765 100644 --- a/src/n0309_best_time_to_buy_and_sell_stock_with_cooldown.rs +++ b/src/n0309_best_time_to_buy_and_sell_stock_with_cooldown.rs @@ -23,14 +23,16 @@ pub struct Solution {} // submission codes start here /* - dp[i]: max profit with selling at day i - dp2[i]: max profit till day i +dp[i]: max profit with selling at day i +dp2[i]: max profit till day i - dp[i] = max(dp[i-1] + p[i] - p[i-1], dp2[i-2], dp2[i-3] + p[i] - p[i-1]) - */ +dp[i] = max(dp[i-1] + p[i] - p[i-1], dp2[i-2], dp2[i-3] + p[i] - p[i-1]) +*/ impl Solution { pub fn max_profit(prices: Vec) -> i32 { - if prices.len() < 2 { return 0 } + if prices.len() < 2 { + return 0; + } if prices.len() == 2 { return i32::max(0, prices[1] - prices[0]); } @@ -41,16 +43,14 @@ impl Solution { dp2[0] = 0; dp[1] = prices[1] - prices[0]; dp2[1] = i32::max(dp2[0], dp[1]); - dp[2] = i32::max(prices[2] - prices[1], prices[2]-prices[0]); + dp[2] = i32::max(prices[2] - prices[1], prices[2] - prices[0]); dp2[2] = i32::max(dp2[1], dp[2]); for i in 3..prices.len() { - dp[i] = i32::max(dp[i-1]+prices[i]-prices[i-1], - i32::max( - dp2[i-2], - dp2[i-3]+prices[i]-prices[i-1] - ) + dp[i] = i32::max( + dp[i - 1] + prices[i] - prices[i - 1], + i32::max(dp2[i - 2], dp2[i - 3] + prices[i] - prices[i - 1]), ); - dp2[i] = i32::max(dp2[i-1], dp[i]); + dp2[i] = i32::max(dp2[i - 1], dp[i]); } let mut temp = 0; for &m in dp.iter() { @@ -70,7 +70,7 @@ mod tests { #[test] fn test_309() { - assert_eq!(Solution::max_profit(vec![1,2,3,0,2]), 3); - assert_eq!(Solution::max_profit(vec![4,2,7,1,11]), 10); + assert_eq!(Solution::max_profit(vec![1, 2, 3, 0, 2]), 3); + assert_eq!(Solution::max_profit(vec![4, 2, 7, 1, 11]), 10); } } diff --git a/src/n0310_minimum_height_trees.rs b/src/n0310_minimum_height_trees.rs index ed78bade..ab1337e2 100644 --- a/src/n0310_minimum_height_trees.rs +++ b/src/n0310_minimum_height_trees.rs @@ -91,8 +91,17 @@ mod tests { #[test] fn test_310() { - assert_eq!(Solution::find_min_height_trees(4, vec![vec![1, 0], vec![1, 2], vec![1, 3]]), vec![1]); - assert_eq!(Solution::find_min_height_trees(6, vec![vec![0, 3], vec![1, 3], vec![2, 3], vec![4, 3], vec![5, 4]]), vec![3, 4]); + assert_eq!( + Solution::find_min_height_trees(4, vec![vec![1, 0], vec![1, 2], vec![1, 3]]), + vec![1] + ); + assert_eq!( + Solution::find_min_height_trees( + 6, + vec![vec![0, 3], vec![1, 3], vec![2, 3], vec![4, 3], vec![5, 4]] + ), + vec![3, 4] + ); assert_eq!(Solution::find_min_height_trees(1, vec![]), vec![0]); } } diff --git a/src/n0312_burst_balloons.rs b/src/n0312_burst_balloons.rs index 15332726..689db341 100644 --- a/src/n0312_burst_balloons.rs +++ b/src/n0312_burst_balloons.rs @@ -26,27 +26,27 @@ pub struct Solution {} // submission codes start here /* - The key idea is, for a sequence of balloon, select a balloon to be the last one to be bursted: +The key idea is, for a sequence of balloon, select a balloon to be the last one to be bursted: - max of [1 . a b c d e f . 1] +max of [1 . a b c d e f . 1] - ^ say we select 'c' as the last balloon to burst, then: + ^ say we select 'c' as the last balloon to burst, then: - = - max of [1 . a b . c] + += + max of [1 . a b . c] + - max of [c . d e f . 1] + + max of [c . d e f . 1] + - 1 * c * 1 + 1 * c * 1 - Then we can use memorize to record the max of every sub sequence - */ +Then we can use memorize to record the max of every sub sequence +*/ impl Solution { pub fn max_coins(nums: Vec) -> i32 { if nums.is_empty() { - return 0 + return 0; } - let mut coins = vec![0; nums.len()+2]; + let mut coins = vec![0; nums.len() + 2]; let mut len = 0_usize; // filter out zeros for &num in nums.iter() { @@ -56,28 +56,39 @@ impl Solution { } } coins[0] = 1; - coins[len+1] = 1; + coins[len + 1] = 1; - let mut memo = vec![vec![0; len+1]; len+1]; + let mut memo = vec![vec![0; len + 1]; len + 1]; Solution::max_subrange(&coins, 1, len, &mut memo) } fn max_subrange(coins: &Vec, start: usize, end: usize, memo: &mut Vec>) -> i32 { if memo[start][end] != 0 { - return memo[start][end] + return memo[start][end]; } if start == end { - memo[start][end] = coins[start-1] * coins[start] * coins[start+1]; - return memo[start][end] + memo[start][end] = coins[start - 1] * coins[start] * coins[start + 1]; + return memo[start][end]; } let mut max = 0; - for i in start..end+1 { - let left_max = if i > start { Solution::max_subrange(coins, start, i-1, memo) } else { 0 }; - let right_max = if i < end { Solution::max_subrange(coins, i+1, end, memo) } else { 0 }; - max = i32::max(max, left_max + right_max + coins[i] * coins[start-1] * coins[end+1]); + for i in start..end + 1 { + let left_max = if i > start { + Solution::max_subrange(coins, start, i - 1, memo) + } else { + 0 + }; + let right_max = if i < end { + Solution::max_subrange(coins, i + 1, end, memo) + } else { + 0 + }; + max = i32::max( + max, + left_max + right_max + coins[i] * coins[start - 1] * coins[end + 1], + ); } memo[start][end] = max; - return memo[start][end] + return memo[start][end]; } } @@ -89,6 +100,6 @@ mod tests { #[test] fn test_312() { - assert_eq!(Solution::max_coins(vec![3,1,5,8]), 167); + assert_eq!(Solution::max_coins(vec![3, 1, 5, 8]), 167); } } diff --git a/src/n0313_super_ugly_number.rs b/src/n0313_super_ugly_number.rs index f2bc84b8..78c54fa8 100644 --- a/src/n0313_super_ugly_number.rs +++ b/src/n0313_super_ugly_number.rs @@ -27,8 +27,8 @@ pub struct Solution {} // submission codes start here -use std::collections::BinaryHeap; use std::cmp::Ordering; +use std::collections::BinaryHeap; #[derive(Eq, PartialEq)] struct Invert { base: i32, @@ -44,18 +44,22 @@ impl Ord for Invert { impl PartialOrd for Invert { fn partial_cmp(&self, other: &Invert) -> Option { - Some(self.cmp(other)) + Some(self.cmp(other)) } } impl Solution { pub fn nth_super_ugly_number(n: i32, primes: Vec) -> i32 { - let mut vec = vec![1;1]; + let mut vec = vec![1; 1]; let mut heap: BinaryHeap = BinaryHeap::new(); for &prime in primes.iter() { - heap.push(Invert{base: prime, idx: 0, value: prime}); + heap.push(Invert { + base: prime, + idx: 0, + value: prime, + }); } - for _ in 0..n-1 { + for _ in 0..n - 1 { let mut min = 0; if let Some(num) = heap.peek() { min = num.value; @@ -63,7 +67,11 @@ impl Solution { vec.push(min); while heap.peek().unwrap().value == min { let p = heap.pop().unwrap(); - heap.push(Invert{base: p.base, idx: p.idx+1, value: p.base * vec[p.idx+1]}); + heap.push(Invert { + base: p.base, + idx: p.idx + 1, + value: p.base * vec[p.idx + 1], + }); } } *vec.last().unwrap() @@ -78,6 +86,6 @@ mod tests { #[test] fn test_313() { - assert_eq!(Solution::nth_super_ugly_number(12, vec![2,7,13,19]), 32); + assert_eq!(Solution::nth_super_ugly_number(12, vec![2, 7, 13, 19]), 32); } } diff --git a/src/n1009_pancake_sorting.rs b/src/n1009_pancake_sorting.rs index 54bf15c3..6a32ea04 100644 --- a/src/n1009_pancake_sorting.rs +++ b/src/n1009_pancake_sorting.rs @@ -2,45 +2,45 @@ * [1009] Pancake Sorting * * Given an array A, we can perform a pancake flip: We choose some positive integer k <= A.length, then reverse the order of the first k elements of A. We want to perform zero or more pancake flips (doing them one after another in succession) to sort the array A. - * + * * Return the k-values corresponding to a sequence of pancake flips that sort A. Any valid answer that sorts the array within 10 * A.length flips will be judged as correct. - * + * * - * + * * Example 1: - * - * + * + * * Input: [3,2,4,1] * Output: [4,2,4,3] - * Explanation: + * Explanation: * We perform 4 pancake flips, with k values 4, 2, 4, and 3. * Starting state: A = [3, 2, 4, 1] * After 1st flip (k=4): A = [1, 4, 2, 3] * After 2nd flip (k=2): A = [4, 1, 2, 3] * After 3rd flip (k=4): A = [3, 2, 1, 4] - * After 4th flip (k=3): A = [1, 2, 3, 4], which is sorted. - * - * + * After 4th flip (k=3): A = [1, 2, 3, 4], which is sorted. + * + * *
* Example 2: - * - * + * + * * Input: [1,2,3] * Output: [] * Explanation: The input is already sorted, so there is no need to flip anything. * Note that other answers, such as [3, 3], would also be accepted. - * - * + * + * * *
- * + * * Note: - * + * *
    * 1 <= A.length <= 100 * A[i] is a permutation of [1, 2, ..., A.length] *
- * + * */ pub struct Solution {} @@ -66,30 +66,30 @@ impl Solution { if index != 0usize { Solution::pancake_oper(&mut b, index, &mut res); } - Solution::pancake_oper(&mut b, (k-1) as usize, &mut res); + Solution::pancake_oper(&mut b, (k - 1) as usize, &mut res); } -// println!("{:?}", b); + // println!("{:?}", b); res } fn find_k(a: &Vec, k: i32) -> usize { - for i in 0..(k-1) { + for i in 0..(k - 1) { if a[i as usize] == k { return i as usize; } } - (k-1) as usize + (k - 1) as usize } pub fn pancake_oper(a: &mut Vec, index: usize, res: &mut Vec) { let mut helper = Vec::new(); - for i in 0..(index+1) { - helper.push(a[index-i]); + for i in 0..(index + 1) { + helper.push(a[index - i]); } - for i in 0..(index+1) { + for i in 0..(index + 1) { a[i] = helper[i]; } - res.push((index+1) as i32); + res.push((index + 1) as i32); } } @@ -98,8 +98,8 @@ impl Solution { #[cfg(test)] mod tests { use super::*; - use rand::{thread_rng, Rng}; use rand::seq::SliceRandom; + use rand::{thread_rng, Rng}; #[test] fn test_1009() { @@ -117,7 +117,7 @@ mod tests { } fn make_sorted_vector(i: i32) -> Vec { - (1..i+1).collect() + (1..i + 1).collect() } fn make_shuffled_vector(a: &Vec) -> Vec { @@ -127,19 +127,18 @@ mod tests { res } - fn apply_pancake_sort_res(shuffled_vecter: &mut Vec, oper: Vec) - { + fn apply_pancake_sort_res(shuffled_vecter: &mut Vec, oper: Vec) { for i in oper { - pancake_oper(shuffled_vecter, (i-1) as usize); + pancake_oper(shuffled_vecter, (i - 1) as usize); } } pub fn pancake_oper(a: &mut Vec, index: usize) { let mut helper = Vec::new(); - for i in 0..(index+1) { - helper.push(a[index-i]); + for i in 0..(index + 1) { + helper.push(a[index - i]); } - for i in 0..(index+1) { + for i in 0..(index + 1) { a[i] = helper[i]; } } diff --git a/src/n1071_binary_prefix_divisible_by_5.rs b/src/n1071_binary_prefix_divisible_by_5.rs index abf79b68..ff05f8c6 100644 --- a/src/n1071_binary_prefix_divisible_by_5.rs +++ b/src/n1071_binary_prefix_divisible_by_5.rs @@ -58,7 +58,8 @@ impl Solution { ret.push(remain == 0); n = remain; } - return ret; + + ret } } diff --git a/src/n1127_last_stone_weight.rs b/src/n1127_last_stone_weight.rs index f9128e85..cf0c81ac 100644 --- a/src/n1127_last_stone_weight.rs +++ b/src/n1127_last_stone_weight.rs @@ -35,10 +35,10 @@ * */ pub struct Solution {} -use std::collections::BinaryHeap; // submission codes start here +use std::collections::BinaryHeap; impl Solution { pub fn last_stone_weight(stones: Vec) -> i32 { let mut heap = BinaryHeap::new(); diff --git a/src/problem.rs b/src/problem.rs index f26bb94c..712135a4 100644 --- a/src/problem.rs +++ b/src/problem.rs @@ -1,7 +1,7 @@ -extern crate serde_json; extern crate reqwest; +extern crate serde_json; -use std::fmt::{Display, Formatter, Error}; +use std::fmt::{Display, Error, Formatter}; const PROBLEMS_URL: &str = "https://leetcode.com/api/problems/algorithms/"; const GRAPHQL_URL: &str = "https://leetcode.com/graphql"; @@ -21,25 +21,29 @@ pub fn get_problem(frontend_question_id: u32) -> Option { let problems = get_problems().unwrap(); for problem in problems.stat_status_pairs.iter() { if problem.stat.frontend_question_id == frontend_question_id { - if problem.paid_only { - return None + return None; } let client = reqwest::Client::new(); - let resp: RawProblem = client.post(GRAPHQL_URL) - .json(&Query::question_query(problem.stat.question_title_slug.as_ref().unwrap())) - .send().unwrap() - .json().unwrap(); + let resp: RawProblem = client + .post(GRAPHQL_URL) + .json(&Query::question_query( + problem.stat.question_title_slug.as_ref().unwrap(), + )) + .send() + .unwrap() + .json() + .unwrap(); return Some(Problem { title: problem.stat.question_title.clone().unwrap(), title_slug: problem.stat.question_title_slug.clone().unwrap(), - code_definition: serde_json::from_str( & resp.data.question.code_definition).unwrap(), + code_definition: serde_json::from_str(&resp.data.question.code_definition).unwrap(), content: resp.data.question.content, sample_test_case: resp.data.question.sample_test_case, difficulty: problem.difficulty.to_string(), question_id: problem.stat.question_id, - }) + }); } } None @@ -70,7 +74,6 @@ pub struct CodeDefinition { pub default_code: String, } - #[derive(Debug, Serialize, Deserialize)] struct Query { #[serde(rename = "operationName")] @@ -83,7 +86,7 @@ impl Query { fn question_query(title_slug: &str) -> Query { Query { operation_name: QUESTION_QUERY_OPERATION.to_owned(), - variables: json!({"titleSlug": title_slug}), + variables: json!({ "titleSlug": title_slug }), query: QUESTION_QUERY_STRING.to_owned(), } } diff --git a/src/util/linked_list.rs b/src/util/linked_list.rs index 6fd4ec6f..37b18e3d 100644 --- a/src/util/linked_list.rs +++ b/src/util/linked_list.rs @@ -1,16 +1,13 @@ #[derive(PartialEq, Eq, Debug)] pub struct ListNode { pub val: i32, - pub next: Option> + pub next: Option>, } impl ListNode { #[inline] pub fn new(val: i32) -> Self { - ListNode { - next: None, - val - } + ListNode { next: None, val } } } diff --git a/src/util/mod.rs b/src/util/mod.rs index b214c465..5a3e5744 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -5,4 +5,4 @@ pub mod vec_string; #[macro_use] pub mod tree; #[macro_use] -pub mod point; \ No newline at end of file +pub mod point; diff --git a/src/util/point.rs b/src/util/point.rs index 1cf308da..3af0c803 100644 --- a/src/util/point.rs +++ b/src/util/point.rs @@ -7,10 +7,7 @@ pub struct Point { impl Point { #[inline] pub fn new(x: i32, y: i32) -> Self { - Point { - x, - y - } + Point { x, y } } } diff --git a/src/util/testing.rs b/src/util/testing.rs index e69de29b..8b137891 100644 --- a/src/util/testing.rs +++ b/src/util/testing.rs @@ -0,0 +1 @@ + diff --git a/src/util/tree.rs b/src/util/tree.rs index 7c3076b1..dacda57d 100644 --- a/src/util/tree.rs +++ b/src/util/tree.rs @@ -1,5 +1,5 @@ -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { @@ -14,7 +14,7 @@ impl TreeNode { TreeNode { val, left: None, - right: None + right: None, } } } @@ -55,4 +55,3 @@ macro_rules! tree { }; ($($e:expr,)*) => {(tree![$($e),*])}; } -