From bce8de1c852c299fabc02912f884f1861283ee67 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Thu, 24 Oct 2024 09:08:13 +0800 Subject: [PATCH] 20241024 finished. --- justfile | 9 +- src/double_week_125/mod.rs | 2 +- src/double_week_125/problem1.rs | 2 +- src/double_week_125/problem2.rs | 7 +- src/double_week_125/problem3.rs | 29 +- src/fetch_problem.rs | 14 +- src/fetch_problem/fetcher.rs | 55 +- src/fetch_problem/manager.rs | 34 +- src/lib.rs | 2 +- src/main.rs | 12 +- src/problem/lcp24_nums_game.rs | 22 +- src/problem/lcp30_magic_tower.rs | 13 +- src/problem/mod.rs | 487 +++++++++--------- src/problem/p100_same_tree.rs | 16 +- src/problem/p101_symmetric_tree.rs | 17 +- .../p102_binary_tree_level_order_traversal.rs | 19 +- ...inary_tree_zigzag_level_order_traversal.rs | 19 +- .../p104_maximum_depth_of_binary_tree.rs | 2 +- ...ree_from_preorder_and_inorder_traversal.rs | 29 +- ...07_binary_tree_level_order_traversal_ii.rs | 19 +- ...vert_sorted_array_to_binary_search_tree.rs | 21 +- src/problem/p112_path_sum.rs | 8 +- .../p1184_distance_between_bus_stops.rs | 22 +- src/problem/p120_triangle.rs | 6 +- .../p121_best_time_to_buy_and_sell_stock.rs | 3 +- ...27_airplane_seat_assignment_probability.rs | 1 - ...123_best_time_to_buy_and_sell_stock_iii.rs | 1 - .../p124_binary_tree_maximum_path_sum.rs | 15 +- src/problem/p125_valid_palindrome.rs | 7 +- ..._elements_in_a_contaminated_binary_tree.rs | 17 +- ...of_burgers_with_no_waste_of_ingredients.rs | 36 +- src/problem/p127_word_ladder.rs | 109 ++-- src/problem/p129_sum_root_to_leaf_numbers.rs | 9 +- src/problem/p130_surrounded_regions.rs | 4 +- src/problem/p136_single_number.rs | 1 - src/problem/p137_single_number_ii.rs | 9 +- src/problem/p139_word_break.rs | 23 +- src/problem/p1436_destination_city.rs | 17 +- .../p144_binary_tree_preorder_traversal.rs | 10 +- ...students_doing_homework_at_a_given_time.rs | 29 +- .../p145_binary_tree_postorder_traversal.rs | 18 +- src/problem/p149_max_points_on_a_line.rs | 16 +- .../p150_evaluate_reverse_polish_notation.rs | 4 +- src/problem/p151_reverse_words_in_a_string.rs | 8 +- ...53_find_minimum_in_rotated_sorted_array.rs | 4 +- src/problem/p155_min_stack.rs | 22 +- src/problem/p162_find_peak_element.rs | 16 +- .../p167_two_sum_ii_input_array_is_sorted.rs | 12 +- src/problem/p1686_stone_game_vi.rs | 23 +- src/problem/p1690_stone_game_vii.rs | 14 +- src/problem/p1696_jump_game_vi.rs | 12 +- src/problem/p169_majority_element.rs | 9 +- src/problem/p172_factorial_trailing_zeroes.rs | 6 +- .../p173_binary_search_tree_iterator.rs | 27 +- .../p1793_maximum_score_of_a_good_subarray.rs | 3 +- ...7_letter_combinations_of_a_phone_number.rs | 8 +- src/problem/p1845_seat_reservation_manager.rs | 19 +- .../p1870_minimum_speed_to_arrive_on_time.rs | 11 +- ...p1884_egg_drop_with_2_eggs_and_n_floors.rs | 1 - ...p188_best_time_to_buy_and_sell_stock_iv.rs | 1 - src/problem/p190_reverse_bits.rs | 6 +- src/problem/p191_number_of_1_bits.rs | 9 +- ...nimum_cost_to_reach_destination_in_time.rs | 11 +- ..._non_zero_product_of_the_array_elements.rs | 7 +- ...number_of_ways_to_arrive_at_destination.rs | 27 +- src/problem/p198_house_robber.rs | 1 - ...ay_where_you_have_been_in_all_the_rooms.rs | 6 +- .../p199_binary_tree_right_side_view.rs | 7 +- src/problem/p1_two_sum.rs | 16 +- src/problem/p200_number_of_islands.rs | 6 +- .../p201_bitwise_and_of_numbers_range.rs | 3 +- ...p2024_maximize_the_confusion_of_an_exam.rs | 19 +- src/problem/p205_isomorphic_strings.rs | 4 +- .../p2073_time_needed_to_buy_tickets.rs | 21 +- src/problem/p207_course_schedule.rs | 16 +- ..._count_common_words_with_one_occurrence.rs | 28 +- src/problem/p209_minimum_size_subarray_sum.rs | 4 +- src/problem/p20_valid_parentheses.rs | 28 +- src/problem/p210_course_schedule_ii.rs | 8 +- ...ign_add_and_search_words_data_structure.rs | 25 +- src/problem/p2129_capitalize_the_title.rs | 11 +- src/problem/p212_word_search_ii.rs | 44 +- .../p215_kth_largest_element_in_an_array.rs | 1 - ..._removing_minimum_number_of_magic_beans.rs | 8 +- .../p2181_merge_nodes_in_between_zeros.rs | 12 +- ...2182_construct_string_with_repeat_limit.rs | 15 +- .../p2187_minimum_time_to_complete_trips.rs | 19 +- src/problem/p219_contains_duplicate_ii.rs | 13 +- src/problem/p21_merge_two_sorted_lists.rs | 14 +- ...mize_number_of_subsequences_in_a_string.rs | 13 +- src/problem/p221_maximal_square.rs | 10 +- src/problem/p222_count_complete_tree_nodes.rs | 9 +- src/problem/p224_basic_calculator.rs | 3 +- .../p225_implement_stack_using_queues.rs | 17 +- src/problem/p226_invert_binary_tree.rs | 14 +- ...p2286_booking_concert_tickets_in_groups.rs | 55 +- src/problem/p228_summary_ranges.rs | 4 +- src/problem/p22_generate_parentheses.rs | 16 +- src/problem/p2306_naming_a_company.rs | 23 +- .../p230_kth_smallest_element_in_a_bst.rs | 11 +- src/problem/p2312_selling_pieces_of_wood.rs | 32 +- .../p232_implement_queue_using_stacks.rs | 15 +- .../p2332_the_latest_time_to_catch_a_bus.rs | 33 +- ...common_ancestor_of_a_binary_search_tree.rs | 25 +- ...p2368_reachable_nodes_with_restrictions.rs | 10 +- ...lowest_common_ancestor_of_a_binary_tree.rs | 19 +- .../p2374_node_with_highest_edge_score.rs | 21 +- src/problem/p2376_count_special_integers.rs | 47 +- .../p2390_removing_stars_from_a_string.rs | 23 +- ..._maximum_number_of_robots_within_budget.rs | 17 +- ...ngest_alphabetical_continuous_substring.rs | 11 +- src/problem/p242_valid_anagram.rs | 8 +- ...t_nodes_queries_in_a_binary_search_tree.rs | 9 +- ...k_of_each_character_from_left_and_right.rs | 13 +- ...n_element_sum_and_digit_sum_of_an_array.rs | 1 - .../p2549_count_distinct_numbers_on_board.rs | 10 +- .../p2552_count_increasing_quadruplets.rs | 15 +- .../p2555_maximize_win_from_two_segments.rs | 9 +- ...find_the_divisibility_array_of_a_string.rs | 10 +- ...nd_the_maximum_number_of_marked_indices.rs | 1 - ...581_count_number_of_possible_root_nodes.rs | 70 ++- .../p2583_kth_largest_sum_in_a_binary_tree.rs | 11 +- ...nimum_number_of_visited_cells_in_a_grid.rs | 17 +- .../p2641_cousins_in_binary_tree_ii.rs | 32 +- ...ign_graph_with_shortest_path_calculator.rs | 1 - ...2670_find_the_distinct_difference_array.rs | 7 +- src/problem/p2671_frequency_tracker.rs | 23 +- ...e_costs_of_paths_equal_in_a_binary_tree.rs | 3 +- ...7_lexicographically_smallest_palindrome.rs | 20 +- ...p26_remove_duplicates_from_sorted_array.rs | 6 +- .../p2708_maximum_strength_of_a_group.rs | 5 +- src/problem/p2719_count_of_integers.rs | 52 +- ...744_find_maximum_number_of_string_pairs.rs | 4 +- src/problem/p274_h_index.rs | 2 +- .../p2765_longest_alternating_subarray.rs | 9 +- .../p2788_split_strings_by_separator.rs | 4 +- ...ment_in_an_array_after_merge_operations.rs | 21 +- src/problem/p27_remove_element.rs | 3 +- ...um_seconds_to_equalize_a_circular_array.rs | 5 +- ...inimum_time_to_make_array_sum_at_most_x.rs | 13 +- ...heck_if_a_string_is_an_acronym_of_words.rs | 35 +- ...nimum_possible_sum_of_a_beautiful_array.rs | 10 +- ...ge_weight_equilibrium_queries_in_a_tree.rs | 57 +- .../p2848_points_that_intersect_with_cars.rs | 11 +- ...um_of_values_at_indices_with_k_set_bits.rs | 16 +- src/problem/p2860_happy_students.rs | 9 +- src/problem/p2861_maximum_number_of_alloys.rs | 38 +- .../p2864_maximum_odd_binary_number.rs | 12 +- src/problem/p2865_beautiful_towers_i.rs | 10 +- .../p2867_count_valid_paths_in_a_tree.rs | 33 +- src/problem/p289_game_of_life.rs | 17 +- ...dex_of_the_first_occurrence_in_a_string.rs | 8 +- ...2908_minimum_sum_of_mountain_triplets_i.rs | 10 +- src/problem/p290_word_pattern.rs | 10 +- .../p2917_find_the_k_or_of_an_array.rs | 3 +- src/problem/p292_nim_game.rs | 1 - .../p295_find_median_from_data_stream.rs | 34 +- src/problem/p299_bulls_and_cows.rs | 11 +- src/problem/p2_add_two_numbers.rs | 32 +- ...f_the_prices_is_less_than_or_equal_to_k.rs | 17 +- .../p300_longest_increasing_subsequence.rs | 19 +- ...bstring_with_concatenation_of_all_words.rs | 11 +- src/problem/p310_minimum_height_trees.rs | 14 +- ...minimum_sum_of_values_by_dividing_array.rs | 19 +- ...p3127_make_a_square_with_the_same_color.rs | 12 +- src/problem/p3133_minimum_array_end.rs | 11 +- ...find_the_median_of_the_uniqueness_array.rs | 1 - ...r_of_operations_to_make_word_k_periodic.rs | 7 +- ...3142_check_if_grid_satisfies_conditions.rs | 17 +- ..._partition_of_equal_character_frequency.rs | 23 +- ..._find_products_of_elements_of_big_array.rs | 13 +- ...mutation_difference_between_two_strings.rs | 16 +- ...3_sum_of_digit_differences_of_all_pairs.rs | 11 +- ..._number_of_ways_to_reach_the_k_th_stair.rs | 15 +- ...d_the_xor_of_numbers_which_appear_twice.rs | 1 - .../p3162_find_the_number_of_good_pairs_i.rs | 22 +- .../p3164_find_the_number_of_good_pairs_ii.rs | 11 +- ...d_subarray_with_bitwise_or_closest_to_k.rs | 11 +- src/problem/p3174_clear_digits.rs | 18 +- ...he_first_player_to_win_k_games_in_a_row.rs | 45 ++ ..._maximum_length_of_a_good_subsequence_i.rs | 3 +- ...maximum_length_of_a_good_subsequence_ii.rs | 4 +- ..._count_pairs_that_form_a_complete_day_i.rs | 6 +- ...count_pairs_that_form_a_complete_day_ii.rs | 8 +- ...ke_binary_array_elements_equal_to_one_i.rs | 7 +- ...e_binary_array_elements_equal_to_one_ii.rs | 1 - .../p3193_count_the_number_of_inversions.rs | 23 +- ...verage_of_smallest_and_largest_elements.rs | 6 +- .../p3200_maximum_height_of_a_triangle.rs | 1 - src/problem/p322_coin_change.rs | 3 +- ...preorder_serialization_of_a_binary_tree.rs | 5 +- .../p33_search_in_rotated_sorted_array.rs | 24 +- ...ast_position_of_element_in_sorted_array.rs | 10 +- src/problem/p35_search_insert_position.rs | 4 +- src/problem/p365_water_and_jug_problem.rs | 3 +- .../p373_find_k_pairs_with_smallest_sums.rs | 19 +- .../p380_insert_delete_getrandom_o1.rs | 23 +- src/problem/p383_ransom_note.rs | 5 +- src/problem/p392_is_subsequence.rs | 8 +- src/problem/p399_evaluate_division.rs | 22 +- src/problem/p39_combination_sum.rs | 17 +- ..._substring_without_repeating_characters.rs | 31 +- src/problem/p410_split_array_largest_sum.rs | 7 +- src/problem/p447_number_of_boomerangs.rs | 21 +- ...imum_number_of_arrows_to_burst_balloons.rs | 10 +- src/problem/p46_permutations.rs | 9 +- src/problem/p48_rotate_image.rs | 6 +- src/problem/p49_group_anagrams.rs | 7 +- src/problem/p4_median_of_two_sorted_arrays.rs | 50 +- src/problem/p502_ipo.rs | 14 +- src/problem/p50_powx_n.rs | 10 +- src/problem/p514_freedom_trail.rs | 20 +- src/problem/p52_n_queens_ii.rs | 14 +- ...p530_minimum_absolute_difference_in_bst.rs | 9 +- src/problem/p53_maximum_subarray.rs | 4 +- .../p551_student_attendance_record_i.rs | 12 +- .../p552_student_attendance_record_ii.rs | 19 +- src/problem/p55_jump_game.rs | 2 +- src/problem/p57_insert_interval.rs | 4 +- src/problem/p58_length_of_last_word.rs | 15 +- .../p637_average_of_levels_in_binary_tree.rs | 7 +- src/problem/p63_unique_paths_ii.rs | 16 +- src/problem/p64_minimum_path_sum.rs | 6 +- src/problem/p66_plus_one.rs | 5 +- src/problem/p670_maximum_swap.rs | 1 - src/problem/p67_add_binary.rs | 46 +- src/problem/p68_text_justification.rs | 21 +- .../p698_partition_to_k_equal_sum_subsets.rs | 10 +- src/problem/p69_sqrtx.rs | 6 +- src/problem/p6_zigzag_conversion.rs | 31 +- src/problem/p70_climbing_stairs.rs | 7 +- src/problem/p71_simplify_path.rs | 10 +- src/problem/p72_edit_distance.rs | 27 +- src/problem/p743_network_delay_time.rs | 32 +- src/problem/p74_search_a_2d_matrix.rs | 11 +- src/problem/p76_minimum_window_substring.rs | 12 +- src/problem/p77_combinations.rs | 4 +- src/problem/p79_word_search.rs | 18 +- src/problem/p7_reverse_integer.rs | 22 +- ..._remove_duplicates_from_sorted_array_ii.rs | 7 +- src/problem/p815_bus_routes.rs | 20 +- ...2_remove_duplicates_from_sorted_list_ii.rs | 9 +- .../p83_remove_duplicates_from_sorted_list.rs | 7 +- .../p871_minimum_number_of_refueling_stops.rs | 10 +- src/problem/p887_super_egg_drop.rs | 3 +- ...e_from_preorder_and_postorder_traversal.rs | 1 - src/problem/p88_merge_sorted_array.rs | 4 +- src/problem/p908_smallest_range_i.rs | 1 - src/problem/p910_smallest_range_ii.rs | 1 - src/problem/p912_sort_an_array.rs | 17 +- .../p918_maximum_sum_circular_subarray.rs | 4 +- src/problem/p938_range_sum_of_bst.rs | 22 +- .../p94_binary_tree_inorder_traversal.rs | 7 +- src/problem/p977_squares_of_a_sorted_array.rs | 11 +- src/problem/p97_interleaving_string.rs | 13 +- src/problem/p983_minimum_cost_for_tickets.rs | 30 +- ...rtical_order_traversal_of_a_binary_tree.rs | 43 +- .../p98_validate_binary_search_tree.rs | 9 +- src/problem/p993_cousins_in_binary_tree.rs | 18 +- src/problem/p997_find_the_town_judge.rs | 1 - src/problem/p9_palindrome_number.rs | 18 +- src/week_385/problem1.rs | 8 +- src/week_385/problem2.rs | 6 +- src/week_416/mod.rs | 2 +- src/week_416/problem1.rs | 12 +- src/week_416/problem2.rs | 30 +- 266 files changed, 2321 insertions(+), 2014 deletions(-) create mode 100644 src/problem/p3175_find_the_first_player_to_win_k_games_in_a_row.rs diff --git a/justfile b/justfile index 379f5da..f58220b 100755 --- a/justfile +++ b/justfile @@ -6,10 +6,13 @@ update: build: update cargo build --release -test: +fmt: + cargo fmt + +test: fmt cargo test -commit: +commit: test #!/usr/bin/env bash set -euxo pipefail time=$(date "+%Y%m%d") @@ -20,4 +23,4 @@ commit: git push pull id: build - ./target/release/leetcode-rust {{id}} \ No newline at end of file + ./target/release/leetcode-rust {{id}} diff --git a/src/double_week_125/mod.rs b/src/double_week_125/mod.rs index 17371d2..cffe341 100644 --- a/src/double_week_125/mod.rs +++ b/src/double_week_125/mod.rs @@ -1,3 +1,3 @@ mod problem1; mod problem2; -mod problem3; \ No newline at end of file +mod problem3; diff --git a/src/double_week_125/problem1.rs b/src/double_week_125/problem1.rs index a861d38..5f8eeb6 100644 --- a/src/double_week_125/problem1.rs +++ b/src/double_week_125/problem1.rs @@ -12,4 +12,4 @@ impl Solution { result } -} \ No newline at end of file +} diff --git a/src/double_week_125/problem2.rs b/src/double_week_125/problem2.rs index 7f9c60c..7cfa68f 100644 --- a/src/double_week_125/problem2.rs +++ b/src/double_week_125/problem2.rs @@ -1,13 +1,13 @@ pub struct Solution; -use std::collections::BinaryHeap; use std::cmp::Reverse; +use std::collections::BinaryHeap; impl Solution { pub fn min_operations(nums: Vec, k: i32) -> i32 { let mut heap = BinaryHeap::new(); let k = k as i64; - + for i in nums { let i = i as i64; heap.push(Reverse(i)); @@ -23,7 +23,6 @@ impl Solution { result += 1; } - result } -} \ No newline at end of file +} diff --git a/src/double_week_125/problem3.rs b/src/double_week_125/problem3.rs index 8c469e1..b882dc0 100644 --- a/src/double_week_125/problem3.rs +++ b/src/double_week_125/problem3.rs @@ -5,7 +5,7 @@ use std::collections::HashMap; impl Solution { pub fn count_pairs_of_connectable_servers(edges: Vec>, signal_speed: i32) -> Vec { let n = edges.len(); - let mut graph = vec![vec![];n]; + let mut graph = vec![vec![]; n]; let signal_speed = signal_speed as i64; for edge in &edges { @@ -17,17 +17,22 @@ impl Solution { graph[y].push((x, weight)); } - let mut connection = vec![(0,0);n]; - for next in &graph[0] { - - } + let mut connection = vec![(0, 0); n]; + for next in &graph[0] {} let mut result = Vec::with_capacity(n); result } - fn dfs(graph: &Vec>, conection: &mut Vec<(i64, usize)>, now: usize, pre: usize, distance: i64, start: usize) { + fn dfs( + graph: &Vec>, + conection: &mut Vec<(i64, usize)>, + now: usize, + pre: usize, + distance: i64, + start: usize, + ) { for next in &graph[now] { if next.0 == pre { continue; @@ -39,8 +44,14 @@ impl Solution { } } - fn tree_dp(graph: &Vec>, conection: &mut Vec<(i64, usize)>, result: &mut Vec, - now: usize, pre: usize, signal_speed: i64) { + fn tree_dp( + graph: &Vec>, + conection: &mut Vec<(i64, usize)>, + result: &mut Vec, + now: usize, + pre: usize, + signal_speed: i64, + ) { let mut count = HashMap::new(); for node in conection { @@ -68,4 +79,4 @@ impl Solution { } } } -} \ No newline at end of file +} diff --git a/src/fetch_problem.rs b/src/fetch_problem.rs index 6c3867a..a9c886a 100644 --- a/src/fetch_problem.rs +++ b/src/fetch_problem.rs @@ -9,7 +9,7 @@ pub struct CodeDefinition { pub value: String, pub text: String, #[serde(rename = "defaultCode")] - pub default_code: String + pub default_code: String, } /// LeetCode 单个问题 @@ -19,7 +19,7 @@ pub struct Problem { pub content: String, pub code_definition: Vec, pub question_id: u32, - pub return_type: String + pub return_type: String, } #[derive(Serialize, Deserialize)] @@ -47,7 +47,7 @@ pub struct StatWithStatus { #[derive(Serialize, Deserialize)] pub struct Problems { - pub stat_status_pairs: Vec + pub stat_status_pairs: Vec, } const QUESTION_QUERY_STRING: &str = r#" @@ -68,7 +68,7 @@ pub struct Query { #[serde(rename = "operationName")] operation_name: String, variables: serde_json::Value, - query: String + query: String, } impl Query { @@ -78,15 +78,15 @@ impl Query { variables: json!({ "titleSlug": title }), - query: QUESTION_QUERY_STRING.to_owned() + query: QUESTION_QUERY_STRING.to_owned(), } } } pub struct Fetcher { - client: reqwest::Client + client: reqwest::Client, } pub struct ProblemManager { pub problem_list: Vec, -} \ No newline at end of file +} diff --git a/src/fetch_problem/fetcher.rs b/src/fetch_problem/fetcher.rs index 5fc4c10..c6639d4 100644 --- a/src/fetch_problem/fetcher.rs +++ b/src/fetch_problem/fetcher.rs @@ -1,6 +1,6 @@ -use std::error::Error; +use super::{Fetcher, Problem, Problems, Query}; use serde_derive::{Deserialize, Serialize}; -use super::{Problem, Problems, Query, Fetcher}; +use std::error::Error; const PROBLEMS_URL: &str = "https://leetcode.cn/api/problems/algorithms/"; const GRAPHQL_URL: &str = "https://leetcode.cn/graphql"; @@ -8,16 +8,12 @@ const GRAPHQL_URL: &str = "https://leetcode.cn/graphql"; impl Fetcher { pub fn new() -> Fetcher { Fetcher { - client: reqwest::Client::new() + client: reqwest::Client::new(), } } pub async fn get_problems(&self) -> Result { - Ok(reqwest::get(PROBLEMS_URL) - .await? - .json() - .await? - ) + Ok(reqwest::get(PROBLEMS_URL).await?.json().await?) } pub async fn get_problem(self, question_id: u32) -> Result> { @@ -28,19 +24,18 @@ impl Fetcher { Ok(id) => { if id == question_id { if problem.paid_only { - return Err("failed to get paid only problem".into()) + return Err("failed to get paid only problem".into()); } let query = match &problem.stat.question_title_slug { - None => { - Err::>("failed to get problem title slug".into()) - } - Some(value) => { - Ok(Query::new(value.as_str())) - } + None => Err::>( + "failed to get problem title slug".into(), + ), + Some(value) => Ok(Query::new(value.as_str())), }?; - let response = self.client + let response = self + .client .post(GRAPHQL_URL) .json(&query) .send() @@ -48,20 +43,24 @@ impl Fetcher { .json::() .await?; - let title = problem.stat.question_title.clone() + let title = problem + .stat + .question_title + .clone() .ok_or::>("failed to get problem title".into())?; - let title_slug = problem.stat.question_title_slug.clone() + let title_slug = problem + .stat + .question_title_slug + .clone() .ok_or::>("failed to get problem title slug".into())?; let return_type = { let v = serde_json::from_str::( - &response.data.question.meta_data); - v.and_then(|x| { - return Ok(x.to_string().replace("\"", "")) - }) + &response.data.question.meta_data, + ); + v.and_then(|x| return Ok(x.to_string().replace("\"", ""))) }?; - let code_definition = serde_json::from_str( - &response.data.question.code_definition - )?; + let code_definition = + serde_json::from_str(&response.data.question.code_definition)?; return Ok(Problem { title, @@ -69,8 +68,8 @@ impl Fetcher { code_definition, content: response.data.question.content, question_id: id, - return_type - }) + return_type, + }); } } Err(_) => {} @@ -101,4 +100,4 @@ struct Question { sample_test_case: String, #[serde(rename = "metaData")] meta_data: String, -} \ No newline at end of file +} diff --git a/src/fetch_problem/manager.rs b/src/fetch_problem/manager.rs index 7a12977..5879448 100644 --- a/src/fetch_problem/manager.rs +++ b/src/fetch_problem/manager.rs @@ -1,6 +1,6 @@ use super::{Problem, ProblemManager}; +use regex::Regex; use std::fs; -use regex::{Regex}; impl ProblemManager { pub fn scan() -> Result> { @@ -11,45 +11,43 @@ impl ProblemManager { for i in pattern.captures_iter(&mod_content) { match i.get(1) { None => {} - Some(value) => { - match value.as_str().parse::() { - Ok(id) => { - problems.push(id); - } - Err(_) => {} + Some(value) => match value.as_str().parse::() { + Ok(id) => { + problems.push(id); } - } + Err(_) => {} + }, } } Ok(ProblemManager { - problem_list: problems + problem_list: problems, }) } } impl Problem { pub fn get_filename(&self) -> String { - format!("p{}_{}", self.question_id, self.title_slug.replace('-', "_")) + format!( + "p{}_{}", + self.question_id, + self.title_slug.replace('-', "_") + ) } pub fn get_file_content(&self) -> Result> { let template = fs::read_to_string("./template.rs")?; - let code = self.code_definition - .iter() - .find(|x| x.value == "rust"); + let code = self.code_definition.iter().find(|x| x.value == "rust"); let code = code.ok_or::>( - format!("problem {} doesn't have rust version", self.question_id).into() + format!("problem {} doesn't have rust version", self.question_id).into(), )?; let source = template .replace("__PROBLEM_TITLE__", &self.title) .replace("__PROBLEM_ID__", self.question_id.to_string().as_str()) - .replace( - "__PROBLEM_DEFAULT_CODE__", - &code.default_code) + .replace("__PROBLEM_DEFAULT_CODE__", &code.default_code) .replace("__EXTRA_USE__", &parse_extra_use(&code.default_code)); Ok(source) @@ -69,4 +67,4 @@ fn parse_extra_use(code: &str) -> String { extra_use_line.push_str("\nuse crate::util::point::Point;") } extra_use_line -} \ No newline at end of file +} diff --git a/src/lib.rs b/src/lib.rs index 1f9bc53..51792fb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,6 @@ #[macro_use] pub mod util; +pub mod double_week_125; pub mod problem; pub mod week_385; pub mod week_416; -pub mod double_week_125; diff --git a/src/main.rs b/src/main.rs index 34b8e87..2d32b98 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,7 @@ +use crate::fetch_problem::{Fetcher, ProblemManager}; use std::fs; use std::io::Write; use std::path::Path; -use crate::fetch_problem::{Fetcher, ProblemManager}; mod fetch_problem; @@ -22,12 +22,16 @@ async fn main() { println!("Try to get problem {}...", id); - let problem = fetcher.get_problem(id).await + let problem = fetcher + .get_problem(id) + .await .expect(&*format!("Failed to get problem {}.", id)); let file_name = problem.get_filename(); println!("Get problem: {}.", file_name); - let content = problem.get_file_content().expect("Failed to format file content"); + let content = problem + .get_file_content() + .expect("Failed to format file content"); write_file(&file_name, &content).expect("Failed to write problem file."); } @@ -55,4 +59,4 @@ fn write_file(file_name: &String, file_content: &String) -> std::io::Result<()> .open("./src/problem/mod.rs")?; write!(mod_file, "\nmod {};", file_name) -} \ No newline at end of file +} diff --git a/src/problem/lcp24_nums_game.rs b/src/problem/lcp24_nums_game.rs index df915c8..5f3061f 100644 --- a/src/problem/lcp24_nums_game.rs +++ b/src/problem/lcp24_nums_game.rs @@ -1,15 +1,14 @@ pub struct Solution {} -use std::collections::BinaryHeap; use std::cmp::Reverse; +use std::collections::BinaryHeap; impl Solution { pub fn nums_game(nums: Vec) -> Vec { let mut result = Vec::with_capacity(nums.len()); let m = 1000000007i64; - let (mut lower, mut upper) = - (BinaryHeap::new(), BinaryHeap::new()); + let (mut lower, mut upper) = (BinaryHeap::new(), BinaryHeap::new()); let (mut lower_sum, mut upper_sum) = (0i64, 0i64); for (index, value) in nums.iter().enumerate() { @@ -41,10 +40,9 @@ impl Solution { } if (index + 1) % 2 == 0 { - result.push(((upper_sum - lower_sum) % m) as i32 ); + result.push(((upper_sum - lower_sum) % m) as i32); } else { - result.push(((upper_sum - lower_sum + *lower.peek().unwrap() as i64) - % m) as i32); + result.push(((upper_sum - lower_sum + *lower.peek().unwrap() as i64) % m) as i32); } } @@ -58,8 +56,14 @@ mod tests { #[test] fn test_lcp24() { - assert_eq!(Solution::nums_game(vec![3,4,5,1,6,7]), vec![0,0,0,5,6,7]); - assert_eq!(Solution::nums_game(vec![1,2,3,4,5]), vec![0,0,0,0,0]); - assert_eq!(Solution::nums_game(vec![471, 626, 848]), vec![0, 154,375]); + assert_eq!( + Solution::nums_game(vec![3, 4, 5, 1, 6, 7]), + vec![0, 0, 0, 5, 6, 7] + ); + assert_eq!( + Solution::nums_game(vec![1, 2, 3, 4, 5]), + vec![0, 0, 0, 0, 0] + ); + assert_eq!(Solution::nums_game(vec![471, 626, 848]), vec![0, 154, 375]); } } diff --git a/src/problem/lcp30_magic_tower.rs b/src/problem/lcp30_magic_tower.rs index 2f5334e..55134a1 100644 --- a/src/problem/lcp30_magic_tower.rs +++ b/src/problem/lcp30_magic_tower.rs @@ -1,7 +1,7 @@ pub struct Solution {} -use std::collections::BinaryHeap; use std::cmp::Reverse; +use std::collections::BinaryHeap; impl Solution { pub fn magic_tower(nums: Vec) -> i32 { @@ -41,9 +41,10 @@ mod tests { #[test] fn test_lcp30() { - assert_eq!(Solution::magic_tower( - vec![100,100,100,-250,-60,-140,-50,-50,100,150]), 1); - assert_eq!(Solution::magic_tower( - vec![-200,-300,400,0]), -1); + assert_eq!( + Solution::magic_tower(vec![100, 100, 100, -250, -60, -140, -50, -50, 100, 150]), + 1 + ); + assert_eq!(Solution::magic_tower(vec![-200, -300, 400, 0]), -1); } -} \ No newline at end of file +} diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 33b8e77..47422d8 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -1,275 +1,276 @@ -mod p1_two_sum; -mod p9_palindrome_number; -mod p20_valid_parentheses; -mod p2697_lexicographically_smallest_palindrome; -mod p2_add_two_numbers; -mod p3_longest_substring_without_repeating_characters; -mod p162_find_peak_element; -mod p2828_check_if_a_string_is_an_acronym_of_words; -mod p52_n_queens_ii; -mod p912_sort_an_array; -mod p1276_number_of_burgers_with_no_waste_of_ingredients; -mod p6_zigzag_conversion; -mod p7_reverse_integer; -mod p4_median_of_two_sorted_arrays; -mod p743_network_delay_time; -mod p447_number_of_boomerangs; -mod p2085_count_common_words_with_one_occurrence; -mod p2182_construct_string_with_repeat_limit; -mod p83_remove_duplicates_from_sorted_list; -mod p82_remove_duplicates_from_sorted_list_ii; -mod p2719_count_of_integers; -mod p2744_find_maximum_number_of_string_pairs; -mod p2171_removing_minimum_number_of_magic_beans; -mod p2809_minimum_time_to_make_array_sum_at_most_x; -mod p2788_split_strings_by_separator; -mod p410_split_array_largest_sum; -mod p670_maximum_swap; -mod p2765_longest_alternating_subarray; -mod p2865_beautiful_towers_i; -mod p2859_sum_of_values_at_indices_with_k_set_bits; -mod p2846_minimum_edge_weight_equilibrium_queries_in_a_tree; -mod p2861_maximum_number_of_alloys; -mod p365_water_and_jug_problem; -mod p514_freedom_trail; -mod p2808_minimum_seconds_to_equalize_a_circular_array; -mod p2670_find_the_distinct_difference_array; mod lcp24_nums_game; -mod p1686_stone_game_vi; -mod p1690_stone_game_vii; -mod p292_nim_game; -mod p1696_jump_game_vi; mod lcp30_magic_tower; -mod p2641_cousins_in_binary_tree_ii; -mod p993_cousins_in_binary_tree; -mod p236_lowest_common_ancestor_of_a_binary_tree; -mod p94_binary_tree_inorder_traversal; -mod p144_binary_tree_preorder_traversal; -mod p145_binary_tree_postorder_traversal; -mod p987_vertical_order_traversal_of_a_binary_tree; +mod p100_same_tree; +mod p101_symmetric_tree; mod p102_binary_tree_level_order_traversal; -mod p107_binary_tree_level_order_traversal_ii; mod p103_binary_tree_zigzag_level_order_traversal; +mod p104_maximum_depth_of_binary_tree; mod p105_construct_binary_tree_from_preorder_and_inorder_traversal; mod p106_construct_binary_tree_from_inorder_and_postorder_traversal; -mod p235_lowest_common_ancestor_of_a_binary_search_tree; -mod p2583_kth_largest_sum_in_a_binary_tree; -mod p2476_closest_nodes_queries_in_a_binary_search_tree; -mod p938_range_sum_of_bst; -mod p889_construct_binary_tree_from_preorder_and_postorder_traversal; -mod p2867_count_valid_paths_in_a_tree; -mod p2673_make_costs_of_paths_equal_in_a_binary_tree; -mod p2581_count_number_of_possible_root_nodes; -mod p2369_check_if_there_is_a_valid_partition_for_the_array; -mod p2368_reachable_nodes_with_restrictions; -mod p225_implement_stack_using_queues; -mod p232_implement_queue_using_stacks; -mod p1976_number_of_ways_to_arrive_at_destination; -mod p2917_find_the_k_or_of_an_array; -mod p2575_find_the_divisibility_array_of_a_string; -mod p2834_find_the_minimum_possible_sum_of_a_beautiful_array; -mod p2386_find_the_k_sum_of_an_array; -mod p299_bulls_and_cows; -mod p2129_capitalize_the_title; -mod p1261_find_elements_in_a_contaminated_binary_tree; -mod p2864_maximum_odd_binary_number; -mod p2789_largest_element_in_an_array_after_merge_operations; -mod p2312_selling_pieces_of_wood; -mod p2684_maximum_number_of_moves_in_a_grid; -mod p310_minimum_height_trees; -mod p303_range_sum_query_immutable; -mod p1793_maximum_score_of_a_good_subarray; -mod p1969_minimum_non_zero_product_of_the_array_elements; -mod p2671_frequency_tracker; -mod p2617_minimum_number_of_visited_cells_in_a_grid; -mod p2549_count_distinct_numbers_on_board; -mod p322_coin_change; -mod p518_coin_change_ii; -mod p2642_design_graph_with_shortest_path_calculator; -mod p2580_count_ways_to_group_overlapping_ranges; -mod p1997_first_day_where_you_have_been_in_all_the_rooms; -mod p2908_minimum_sum_of_mountain_triplets_i; -mod p2952_minimum_number_of_coins_to_be_added; -mod p331_verify_preorder_serialization_of_a_binary_tree; -mod p88_merge_sorted_array; -mod p26_remove_duplicates_from_sorted_array; -mod p27_remove_element; -mod p80_remove_duplicates_from_sorted_array_ii; -mod p169_majority_element; -mod p189_rotate_array; +mod p107_binary_tree_level_order_traversal_ii; +mod p108_convert_sorted_array_to_binary_search_tree; +mod p112_path_sum; +mod p114_flatten_binary_tree_to_linked_list; +mod p120_triangle; mod p121_best_time_to_buy_and_sell_stock; mod p122_best_time_to_buy_and_sell_stock_ii; -mod p55_jump_game; -mod p45_jump_game_ii; -mod p274_h_index; -mod p380_insert_delete_getrandom_o1; -mod p238_product_of_array_except_self; +mod p123_best_time_to_buy_and_sell_stock_iii; +mod p124_binary_tree_maximum_path_sum; +mod p125_valid_palindrome; +mod p1261_find_elements_in_a_contaminated_binary_tree; +mod p1276_number_of_burgers_with_no_waste_of_ingredients; +mod p127_word_ladder; +mod p128_longest_consecutive_sequence; +mod p129_sum_root_to_leaf_numbers; +mod p130_surrounded_regions; mod p134_gas_station; mod p135_candy; -mod p42_trapping_rain_water; -mod p58_length_of_last_word; -mod p151_reverse_words_in_a_string; -mod p28_find_the_index_of_the_first_occurrence_in_a_string; -mod p68_text_justification; -mod p125_valid_palindrome; -mod p392_is_subsequence; -mod p167_two_sum_ii_input_array_is_sorted; -mod p209_minimum_size_subarray_sum; -mod p30_substring_with_concatenation_of_all_words; -mod p76_minimum_window_substring; -mod p36_valid_sudoku; -mod p54_spiral_matrix; -mod p48_rotate_image; -mod p73_set_matrix_zeroes; -mod p289_game_of_life; -mod p383_ransom_note; -mod p290_word_pattern; -mod p205_isomorphic_strings; -mod p242_valid_anagram; -mod p49_group_anagrams; -mod p202_happy_number; -mod p219_contains_duplicate_ii; -mod p128_longest_consecutive_sequence; -mod p228_summary_ranges; -mod p56_merge_intervals; -mod p57_insert_interval; -mod p452_minimum_number_of_arrows_to_burst_balloons; -mod p71_simplify_path; -mod p155_min_stack; -mod p150_evaluate_reverse_polish_notation; -mod p224_basic_calculator; -mod p21_merge_two_sorted_lists; -mod p104_maximum_depth_of_binary_tree; -mod p100_same_tree; -mod p226_invert_binary_tree; -mod p101_symmetric_tree; -mod p114_flatten_binary_tree_to_linked_list; -mod p112_path_sum; -mod p129_sum_root_to_leaf_numbers; -mod p124_binary_tree_maximum_path_sum; -mod p173_binary_search_tree_iterator; -mod p222_count_complete_tree_nodes; -mod p199_binary_tree_right_side_view; -mod p637_average_of_levels_in_binary_tree; -mod p530_minimum_absolute_difference_in_bst; -mod p230_kth_smallest_element_in_a_bst; -mod p98_validate_binary_search_tree; -mod p200_number_of_islands; -mod p130_surrounded_regions; -mod p399_evaluate_division; -mod p207_course_schedule; -mod p210_course_schedule_ii; -mod p909_snakes_and_ladders; -mod p433_minimum_genetic_mutation; -mod p127_word_ladder; -mod p208_implement_trie_prefix_tree; -mod p211_design_add_and_search_words_data_structure; -mod p212_word_search_ii; -mod p17_letter_combinations_of_a_phone_number; -mod p77_combinations; -mod p46_permutations; -mod p39_combination_sum; -mod p22_generate_parentheses; -mod p79_word_search; -mod p108_convert_sorted_array_to_binary_search_tree; -mod p53_maximum_subarray; -mod p918_maximum_sum_circular_subarray; -mod p35_search_insert_position; -mod p74_search_a_2d_matrix; -mod p33_search_in_rotated_sorted_array; -mod p34_find_first_and_last_position_of_element_in_sorted_array; -mod p153_find_minimum_in_rotated_sorted_array; -mod p215_kth_largest_element_in_an_array; -mod p502_ipo; -mod p373_find_k_pairs_with_smallest_sums; -mod p295_find_median_from_data_stream; -mod p67_add_binary; -mod p190_reverse_bits; -mod p191_number_of_1_bits; mod p136_single_number; mod p137_single_number_ii; -mod p201_bitwise_and_of_numbers_range; -mod p66_plus_one; -mod p172_factorial_trailing_zeroes; -mod p69_sqrtx; -mod p50_powx_n; -mod p149_max_points_on_a_line; -mod p70_climbing_stairs; -mod p198_house_robber; mod p139_word_break; -mod p300_longest_increasing_subsequence; -mod p120_triangle; -mod p64_minimum_path_sum; -mod p63_unique_paths_ii; -mod p97_interleaving_string; -mod p72_edit_distance; -mod p123_best_time_to_buy_and_sell_stock_iii; +mod p144_binary_tree_preorder_traversal; +mod p145_binary_tree_postorder_traversal; +mod p149_max_points_on_a_line; +mod p150_evaluate_reverse_polish_notation; +mod p151_reverse_words_in_a_string; +mod p153_find_minimum_in_rotated_sorted_array; +mod p155_min_stack; +mod p162_find_peak_element; +mod p167_two_sum_ii_input_array_is_sorted; +mod p1686_stone_game_vi; +mod p1690_stone_game_vii; +mod p1696_jump_game_vi; +mod p169_majority_element; +mod p172_factorial_trailing_zeroes; +mod p173_binary_search_tree_iterator; +mod p1793_maximum_score_of_a_good_subarray; +mod p17_letter_combinations_of_a_phone_number; mod p188_best_time_to_buy_and_sell_stock_iv; +mod p189_rotate_array; +mod p190_reverse_bits; +mod p191_number_of_1_bits; +mod p1969_minimum_non_zero_product_of_the_array_elements; +mod p1976_number_of_ways_to_arrive_at_destination; +mod p198_house_robber; +mod p1997_first_day_where_you_have_been_in_all_the_rooms; +mod p199_binary_tree_right_side_view; +mod p1_two_sum; +mod p200_number_of_islands; +mod p201_bitwise_and_of_numbers_range; +mod p202_happy_number; +mod p205_isomorphic_strings; +mod p207_course_schedule; +mod p2085_count_common_words_with_one_occurrence; +mod p208_implement_trie_prefix_tree; +mod p209_minimum_size_subarray_sum; +mod p20_valid_parentheses; +mod p210_course_schedule_ii; +mod p211_design_add_and_search_words_data_structure; +mod p2129_capitalize_the_title; +mod p212_word_search_ii; +mod p215_kth_largest_element_in_an_array; +mod p2171_removing_minimum_number_of_magic_beans; +mod p2182_construct_string_with_repeat_limit; +mod p219_contains_duplicate_ii; +mod p21_merge_two_sorted_lists; mod p221_maximal_square; +mod p222_count_complete_tree_nodes; +mod p224_basic_calculator; +mod p225_implement_stack_using_queues; +mod p226_invert_binary_tree; +mod p228_summary_ranges; +mod p22_generate_parentheses; +mod p230_kth_smallest_element_in_a_bst; +mod p2312_selling_pieces_of_wood; +mod p232_implement_queue_using_stacks; +mod p235_lowest_common_ancestor_of_a_binary_search_tree; +mod p2368_reachable_nodes_with_restrictions; +mod p2369_check_if_there_is_a_valid_partition_for_the_array; +mod p236_lowest_common_ancestor_of_a_binary_tree; +mod p2386_find_the_k_sum_of_an_array; +mod p238_product_of_array_except_self; +mod p242_valid_anagram; +mod p2476_closest_nodes_queries_in_a_binary_search_tree; +mod p2549_count_distinct_numbers_on_board; +mod p2575_find_the_divisibility_array_of_a_string; +mod p2580_count_ways_to_group_overlapping_ranges; +mod p2581_count_number_of_possible_root_nodes; +mod p2583_kth_largest_sum_in_a_binary_tree; +mod p2617_minimum_number_of_visited_cells_in_a_grid; +mod p2641_cousins_in_binary_tree_ii; +mod p2642_design_graph_with_shortest_path_calculator; +mod p2670_find_the_distinct_difference_array; +mod p2671_frequency_tracker; +mod p2673_make_costs_of_paths_equal_in_a_binary_tree; +mod p2684_maximum_number_of_moves_in_a_grid; +mod p2697_lexicographically_smallest_palindrome; +mod p26_remove_duplicates_from_sorted_array; +mod p2719_count_of_integers; +mod p2744_find_maximum_number_of_string_pairs; +mod p274_h_index; +mod p2765_longest_alternating_subarray; +mod p2788_split_strings_by_separator; +mod p2789_largest_element_in_an_array_after_merge_operations; +mod p27_remove_element; +mod p2808_minimum_seconds_to_equalize_a_circular_array; +mod p2809_minimum_time_to_make_array_sum_at_most_x; +mod p2828_check_if_a_string_is_an_acronym_of_words; +mod p2834_find_the_minimum_possible_sum_of_a_beautiful_array; +mod p2846_minimum_edge_weight_equilibrium_queries_in_a_tree; +mod p2859_sum_of_values_at_indices_with_k_set_bits; +mod p2861_maximum_number_of_alloys; +mod p2864_maximum_odd_binary_number; +mod p2865_beautiful_towers_i; +mod p2867_count_valid_paths_in_a_tree; +mod p289_game_of_life; +mod p28_find_the_index_of_the_first_occurrence_in_a_string; +mod p2908_minimum_sum_of_mountain_triplets_i; +mod p290_word_pattern; +mod p2917_find_the_k_or_of_an_array; +mod p292_nim_game; +mod p2952_minimum_number_of_coins_to_be_added; +mod p295_find_median_from_data_stream; +mod p299_bulls_and_cows; +mod p2_add_two_numbers; +mod p300_longest_increasing_subsequence; +mod p303_range_sum_query_immutable; +mod p30_substring_with_concatenation_of_all_words; +mod p310_minimum_height_trees; mod p3117_minimum_sum_of_values_by_dividing_array; mod p3137_minimum_number_of_operations_to_make_word_k_periodic; +mod p322_coin_change; +mod p331_verify_preorder_serialization_of_a_binary_tree; +mod p33_search_in_rotated_sorted_array; +mod p34_find_first_and_last_position_of_element_in_sorted_array; +mod p35_search_insert_position; +mod p365_water_and_jug_problem; +mod p36_valid_sudoku; +mod p373_find_k_pairs_with_smallest_sums; +mod p380_insert_delete_getrandom_o1; +mod p383_ransom_note; +mod p392_is_subsequence; +mod p399_evaluate_division; +mod p39_combination_sum; +mod p3_longest_substring_without_repeating_characters; +mod p410_split_array_largest_sum; +mod p42_trapping_rain_water; +mod p433_minimum_genetic_mutation; +mod p447_number_of_boomerangs; +mod p452_minimum_number_of_arrows_to_burst_balloons; +mod p45_jump_game_ii; +mod p46_permutations; +mod p48_rotate_image; +mod p49_group_anagrams; +mod p4_median_of_two_sorted_arrays; +mod p502_ipo; +mod p50_powx_n; +mod p514_freedom_trail; +mod p518_coin_change_ii; +mod p52_n_queens_ii; +mod p530_minimum_absolute_difference_in_bst; +mod p53_maximum_subarray; +mod p54_spiral_matrix; mod p551_student_attendance_record_i; +mod p55_jump_game; +mod p56_merge_intervals; +mod p57_insert_interval; +mod p58_length_of_last_word; +mod p637_average_of_levels_in_binary_tree; +mod p63_unique_paths_ii; +mod p64_minimum_path_sum; +mod p66_plus_one; +mod p670_maximum_swap; +mod p67_add_binary; +mod p68_text_justification; +mod p69_sqrtx; +mod p6_zigzag_conversion; +mod p70_climbing_stairs; +mod p71_simplify_path; +mod p72_edit_distance; +mod p73_set_matrix_zeroes; +mod p743_network_delay_time; +mod p74_search_a_2d_matrix; +mod p76_minimum_window_substring; +mod p77_combinations; +mod p79_word_search; +mod p7_reverse_integer; +mod p80_remove_duplicates_from_sorted_array_ii; +mod p82_remove_duplicates_from_sorted_list_ii; +mod p83_remove_duplicates_from_sorted_list; +mod p889_construct_binary_tree_from_preorder_and_postorder_traversal; +mod p88_merge_sorted_array; +mod p909_snakes_and_ladders; +mod p912_sort_an_array; +mod p918_maximum_sum_circular_subarray; +mod p938_range_sum_of_bst; +mod p94_binary_tree_inorder_traversal; +mod p97_interleaving_string; +mod p987_vertical_order_traversal_of_a_binary_tree; +mod p98_validate_binary_search_tree; +mod p993_cousins_in_binary_tree; +mod p9_palindrome_number; -mod p552_student_attendance_record_ii; -mod p3154_find_number_of_ways_to_reach_the_k_th_stair; -mod p3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k; -mod p3133_minimum_array_end; -mod p3145_find_products_of_elements_of_big_array; -mod p3146_permutation_difference_between_two_strings; -mod p698_partition_to_k_equal_sum_subsets; -mod p3134_find_the_median_of_the_uniqueness_array; -mod p3144_minimum_substring_partition_of_equal_character_frequency; -mod p3142_check_if_grid_satisfies_conditions; -mod p3153_sum_of_digit_differences_of_all_pairs; -mod p3127_make_a_square_with_the_same_color; +mod p1184_distance_between_bus_stops; +mod p1227_airplane_seat_assignment_probability; +mod p1436_destination_city; mod p1450_number_of_students_doing_homework_at_a_given_time; +mod p1845_seat_reservation_manager; +mod p1870_minimum_speed_to_arrive_on_time; +mod p1884_egg_drop_with_2_eggs_and_n_floors; +mod p1928_minimum_cost_to_reach_destination_in_time; mod p2024_maximize_the_confusion_of_an_exam; -mod p2708_maximum_strength_of_a_group; -mod p2860_happy_students; -mod p3174_clear_digits; -mod p3176_find_the_maximum_length_of_a_good_subsequence_i; -mod p3177_find_the_maximum_length_of_a_good_subsequence_ii; -mod p977_squares_of_a_sorted_array; +mod p2073_time_needed_to_buy_tickets; mod p2181_merge_nodes_in_between_zeros; +mod p2187_minimum_time_to_complete_trips; +mod p2207_maximize_number_of_subsequences_in_a_string; +mod p2286_booking_concert_tickets_in_groups; +mod p2306_naming_a_company; +mod p2332_the_latest_time_to_catch_a_bus; +mod p2374_node_with_highest_edge_score; +mod p2376_count_special_integers; +mod p2390_removing_stars_from_a_string; +mod p2398_maximum_number_of_robots_within_budget; +mod p2414_length_of_the_longest_alphabetical_continuous_substring; +mod p2516_take_k_of_each_character_from_left_and_right; +mod p2535_difference_between_element_sum_and_digit_sum_of_an_array; mod p2552_count_increasing_quadruplets; mod p2555_maximize_win_from_two_segments; mod p2576_find_the_maximum_number_of_marked_indices; -mod p2398_maximum_number_of_robots_within_budget; -mod p2390_removing_stars_from_a_string; +mod p2708_maximum_strength_of_a_group; mod p2848_points_that_intersect_with_cars; -mod p1184_distance_between_bus_stops; -mod p815_bus_routes; -mod p2332_the_latest_time_to_catch_a_bus; -mod p2414_length_of_the_longest_alphabetical_continuous_substring; -mod p2376_count_special_integers; -mod p2374_node_with_highest_edge_score; -mod p997_find_the_town_judge; -mod p2207_maximize_number_of_subsequences_in_a_string; -mod p2306_naming_a_company; -mod p2535_difference_between_element_sum_and_digit_sum_of_an_array; -mod p2516_take_k_of_each_character_from_left_and_right; -mod p2286_booking_concert_tickets_in_groups; -mod p2073_time_needed_to_buy_tickets; -mod p1845_seat_reservation_manager; -mod p983_minimum_cost_for_tickets; -mod p1870_minimum_speed_to_arrive_on_time; -mod p1928_minimum_cost_to_reach_destination_in_time; -mod p1227_airplane_seat_assignment_probability; -mod p2187_minimum_time_to_complete_trips; -mod p871_minimum_number_of_refueling_stops; -mod p1436_destination_city; -mod p3171_find_subarray_with_bitwise_or_closest_to_k; +mod p2860_happy_students; +mod p3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k; +mod p3127_make_a_square_with_the_same_color; +mod p3133_minimum_array_end; +mod p3134_find_the_median_of_the_uniqueness_array; +mod p3142_check_if_grid_satisfies_conditions; +mod p3144_minimum_substring_partition_of_equal_character_frequency; +mod p3145_find_products_of_elements_of_big_array; +mod p3146_permutation_difference_between_two_strings; +mod p3153_sum_of_digit_differences_of_all_pairs; +mod p3154_find_number_of_ways_to_reach_the_k_th_stair; +mod p3158_find_the_xor_of_numbers_which_appear_twice; mod p3162_find_the_number_of_good_pairs_i; mod p3164_find_the_number_of_good_pairs_ii; -mod p3158_find_the_xor_of_numbers_which_appear_twice; -mod p1884_egg_drop_with_2_eggs_and_n_floors; -mod p887_super_egg_drop; -mod p3200_maximum_height_of_a_triangle; -mod p3194_minimum_average_of_smallest_and_largest_elements; -mod p3193_count_the_number_of_inversions; +mod p3171_find_subarray_with_bitwise_or_closest_to_k; +mod p3174_clear_digits; +mod p3175_find_the_first_player_to_win_k_games_in_a_row; +mod p3176_find_the_maximum_length_of_a_good_subsequence_i; +mod p3177_find_the_maximum_length_of_a_good_subsequence_ii; +mod p3184_count_pairs_that_form_a_complete_day_i; +mod p3185_count_pairs_that_form_a_complete_day_ii; mod p3191_minimum_operations_to_make_binary_array_elements_equal_to_one_i; mod p3192_minimum_operations_to_make_binary_array_elements_equal_to_one_ii; +mod p3193_count_the_number_of_inversions; +mod p3194_minimum_average_of_smallest_and_largest_elements; +mod p3200_maximum_height_of_a_triangle; +mod p552_student_attendance_record_ii; +mod p698_partition_to_k_equal_sum_subsets; +mod p815_bus_routes; +mod p871_minimum_number_of_refueling_stops; +mod p887_super_egg_drop; mod p908_smallest_range_i; mod p910_smallest_range_ii; -mod p3184_count_pairs_that_form_a_complete_day_i; -mod p3185_count_pairs_that_form_a_complete_day_ii; \ No newline at end of file +mod p977_squares_of_a_sorted_array; +mod p983_minimum_cost_for_tickets; +mod p997_find_the_town_judge; diff --git a/src/problem/p100_same_tree.rs b/src/problem/p100_same_tree.rs index 2fb959b..86caf2e 100644 --- a/src/problem/p100_same_tree.rs +++ b/src/problem/p100_same_tree.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,11 +25,14 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; -use std::collections::VecDeque; use std::cell::RefCell; +use std::collections::VecDeque; +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 { let mut p_queue = VecDeque::new(); let mut q_queue = VecDeque::new(); @@ -66,7 +69,7 @@ impl Solution { if let Some(p_left) = &p_node.borrow().left { if let Some(q_left) = &q_node.borrow().left { p_queue.push_back(Rc::clone(p_left)); - q_queue.push_back(Rc::clone(q_left)); + q_queue.push_back(Rc::clone(q_left)); }; }; @@ -90,6 +93,5 @@ mod tests { use super::*; #[test] - fn test_100() { - } + fn test_100() {} } diff --git a/src/problem/p101_symmetric_tree.rs b/src/problem/p101_symmetric_tree.rs index c2cac57..cdb710c 100644 --- a/src/problem/p101_symmetric_tree.rs +++ b/src/problem/p101_symmetric_tree.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,10 +25,13 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { - fn is_same(left: &Option>>, right: &Option>>) -> bool { + fn is_same( + left: &Option>>, + right: &Option>>, + ) -> bool { if left.is_some() ^ right.is_some() { return false; } @@ -44,7 +47,7 @@ impl Solution { return false; } - Self::is_same(&left.borrow().left, &right.borrow().right) + Self::is_same(&left.borrow().left, &right.borrow().right) && Self::is_same(&left.borrow().right, &right.borrow().left) } @@ -65,7 +68,9 @@ mod tests { #[test] fn test_101() { - assert!(Solution::is_symmetric(tree![1,2,2,3,4,4,3])); - assert!(!Solution::is_symmetric(tree!(1,2,2,"null",3,"null",3))) + assert!(Solution::is_symmetric(tree![1, 2, 2, 3, 4, 4, 3])); + assert!(!Solution::is_symmetric(tree!( + 1, 2, 2, "null", 3, "null", 3 + ))) } } diff --git a/src/problem/p102_binary_tree_level_order_traversal.rs b/src/problem/p102_binary_tree_level_order_traversal.rs index 709fa83..d097626 100644 --- a/src/problem/p102_binary_tree_level_order_traversal.rs +++ b/src/problem/p102_binary_tree_level_order_traversal.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,9 +25,9 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -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> { @@ -72,8 +72,17 @@ mod tests { #[test] fn test_102() { - assert_eq!(Solution::level_order( - to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)]) - ), vec![vec![3], vec![9, 20], vec![15, 7]]); + assert_eq!( + Solution::level_order(to_tree(vec![ + Some(3), + Some(9), + Some(20), + None, + None, + Some(15), + Some(7) + ])), + vec![vec![3], vec![9, 20], vec![15, 7]] + ); } } diff --git a/src/problem/p103_binary_tree_zigzag_level_order_traversal.rs b/src/problem/p103_binary_tree_zigzag_level_order_traversal.rs index ac51120..aba1f2d 100644 --- a/src/problem/p103_binary_tree_zigzag_level_order_traversal.rs +++ b/src/problem/p103_binary_tree_zigzag_level_order_traversal.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,9 +25,9 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -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 root = if let Some(r) = root { @@ -77,8 +77,17 @@ mod tests { #[test] fn test_103() { - assert_eq!(Solution::zigzag_level_order( - to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)]) - ), vec![vec![3], vec![20, 9], vec![15, 7]]); + assert_eq!( + Solution::zigzag_level_order(to_tree(vec![ + Some(3), + Some(9), + Some(20), + None, + None, + Some(15), + Some(7) + ])), + vec![vec![3], vec![20, 9], vec![15, 7]] + ); } } diff --git a/src/problem/p104_maximum_depth_of_binary_tree.rs b/src/problem/p104_maximum_depth_of_binary_tree.rs index 46c1a4e..aa975cf 100644 --- a/src/problem/p104_maximum_depth_of_binary_tree.rs +++ b/src/problem/p104_maximum_depth_of_binary_tree.rs @@ -36,7 +36,7 @@ impl Solution { if let Some(node) = root { queue.push_back(node); - } + } while !queue.is_empty() { let level = queue.len(); diff --git a/src/problem/p105_construct_binary_tree_from_preorder_and_inorder_traversal.rs b/src/problem/p105_construct_binary_tree_from_preorder_and_inorder_traversal.rs index 363dd3a..09200d6 100644 --- a/src/problem/p105_construct_binary_tree_from_preorder_and_inorder_traversal.rs +++ b/src/problem/p105_construct_binary_tree_from_preorder_and_inorder_traversal.rs @@ -5,7 +5,7 @@ pub struct Solution {} use surf::middleware::logger::new; -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -27,16 +27,15 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn build_tree(preorder: Vec, inorder: Vec) -> Option>> { if preorder.len() == 0 { return None; } - let root = Rc::new(RefCell::new( - TreeNode::new(preorder[0]))); + let root = Rc::new(RefCell::new(TreeNode::new(preorder[0]))); let mut stack = Vec::new(); stack.push(Rc::clone(&root)); let mut inorder_index = 0; @@ -45,8 +44,7 @@ impl Solution { let mut node = Rc::clone(stack.last().unwrap()); if node.borrow().val != inorder[inorder_index] { - let new_node = Rc::new(RefCell::new( - TreeNode::new(preorder[i]))); + let new_node = Rc::new(RefCell::new(TreeNode::new(preorder[i]))); stack.push(Rc::clone(&new_node)); node.borrow_mut().left = Some(new_node); } else { @@ -60,8 +58,7 @@ impl Solution { } } - let new_node = Rc::new(RefCell::new( - TreeNode::new(preorder[i]))); + let new_node = Rc::new(RefCell::new(TreeNode::new(preorder[i]))); stack.push(Rc::clone(&new_node)); node.borrow_mut().right = Some(new_node); } @@ -79,9 +76,17 @@ mod tests { #[test] fn test_105() { - assert_eq!(Solution::build_tree( - vec![3,9,20,15,7], - vec![9,3,15,20,7]), - to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)])); + assert_eq!( + Solution::build_tree(vec![3, 9, 20, 15, 7], vec![9, 3, 15, 20, 7]), + to_tree(vec![ + Some(3), + Some(9), + Some(20), + None, + None, + Some(15), + Some(7) + ]) + ); } } diff --git a/src/problem/p107_binary_tree_level_order_traversal_ii.rs b/src/problem/p107_binary_tree_level_order_traversal_ii.rs index 37f0ded..a6a08db 100644 --- a/src/problem/p107_binary_tree_level_order_traversal_ii.rs +++ b/src/problem/p107_binary_tree_level_order_traversal_ii.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,9 +25,9 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -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> { @@ -73,8 +73,17 @@ mod tests { #[test] fn test_107() { - assert_eq!(Solution::level_order_bottom( - to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)]) - ), vec![vec![15, 7], vec![9, 20], vec![3]]); + assert_eq!( + Solution::level_order_bottom(to_tree(vec![ + Some(3), + Some(9), + Some(20), + None, + None, + Some(15), + Some(7) + ])), + vec![vec![15, 7], vec![9, 20], vec![3]] + ); } } diff --git a/src/problem/p108_convert_sorted_array_to_binary_search_tree.rs b/src/problem/p108_convert_sorted_array_to_binary_search_tree.rs index c35ca64..282ef8d 100644 --- a/src/problem/p108_convert_sorted_array_to_binary_search_tree.rs +++ b/src/problem/p108_convert_sorted_array_to_binary_search_tree.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,35 +25,35 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn sorted_array_to_bst(nums: Vec) -> Option>> { Some(Self::array_to_bst(&nums[..])) } - + fn array_to_bst(array: &[i32]) -> Rc> { let length = array.len(); - + if length == 1 { return Rc::new(RefCell::new(TreeNode::new(array[0]))); } - + let middle = length / 2; - + let node = Rc::new(RefCell::new(TreeNode::new(array[middle]))); - + if middle != 0 { // 左边 let left = &array[..middle]; node.borrow_mut().left = Some(Self::array_to_bst(left)); } - + if middle != length - 1 { let right = &array[middle + 1..]; node.borrow_mut().right = Some(Self::array_to_bst(right)); } - + return node; } } @@ -65,6 +65,5 @@ mod tests { use super::*; #[test] - fn test_108() { - } + fn test_108() {} } diff --git a/src/problem/p112_path_sum.rs b/src/problem/p112_path_sum.rs index 8cc1092..08724b7 100644 --- a/src/problem/p112_path_sum.rs +++ b/src/problem/p112_path_sum.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,8 +25,8 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { fn dfs(node: &Rc>, current_sum: i32, target_sum: i32) -> bool { // 到达叶子节点 @@ -49,7 +49,6 @@ impl Solution { false } - pub fn has_path_sum(root: Option>>, target_sum: i32) -> bool { if let Some(root) = root { return Self::dfs(&root, 0, target_sum); @@ -66,6 +65,5 @@ mod tests { use super::*; #[test] - fn test_112() { - } + fn test_112() {} } diff --git a/src/problem/p1184_distance_between_bus_stops.rs b/src/problem/p1184_distance_between_bus_stops.rs index 1847555..ceb6957 100644 --- a/src/problem/p1184_distance_between_bus_stops.rs +++ b/src/problem/p1184_distance_between_bus_stops.rs @@ -3,14 +3,13 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn distance_between_bus_stops(distance: Vec, start: i32, destination: i32) -> i32 { let (start, destination) = (start as usize, destination as usize); let n = distance.len(); - + let mut positive = start; let mut positive_result = 0; @@ -18,7 +17,7 @@ impl Solution { positive_result += distance[positive]; positive = (positive + 1) % n; } - + let mut negative = start; let mut negative_result = 0; @@ -26,7 +25,7 @@ impl Solution { negative = (negative + n - 1) % n; negative_result += distance[negative] } - + positive_result.min(negative_result) } } @@ -39,8 +38,17 @@ mod tests { #[test] fn test_1184() { - assert_eq!(1, Solution::distance_between_bus_stops(vec![1,2,3,4], 0, 1)); - assert_eq!(3, Solution::distance_between_bus_stops(vec![1,2,3,4],0, 2)); - assert_eq!(4, Solution::distance_between_bus_stops(vec![1,2,3,4],0,3)); + assert_eq!( + 1, + Solution::distance_between_bus_stops(vec![1, 2, 3, 4], 0, 1) + ); + assert_eq!( + 3, + Solution::distance_between_bus_stops(vec![1, 2, 3, 4], 0, 2) + ); + assert_eq!( + 4, + Solution::distance_between_bus_stops(vec![1, 2, 3, 4], 0, 3) + ); } } diff --git a/src/problem/p120_triangle.rs b/src/problem/p120_triangle.rs index e94d3f9..878dfab 100644 --- a/src/problem/p120_triangle.rs +++ b/src/problem/p120_triangle.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -37,6 +36,9 @@ mod tests { #[test] fn test_120() { - assert_eq!(11, Solution::minimum_total(vec![vec![2], vec![3, 4], vec![6, 5, 7], vec![4, 1, 8, 3]])); + assert_eq!( + 11, + Solution::minimum_total(vec![vec![2], vec![3, 4], vec![6, 5, 7], vec![4, 1, 8, 3]]) + ); } } diff --git a/src/problem/p121_best_time_to_buy_and_sell_stock.rs b/src/problem/p121_best_time_to_buy_and_sell_stock.rs index f50ad72..000cac7 100644 --- a/src/problem/p121_best_time_to_buy_and_sell_stock.rs +++ b/src/problem/p121_best_time_to_buy_and_sell_stock.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -33,6 +32,6 @@ mod tests { #[test] fn test_121() { - assert_eq!(1, Solution::max_profit(vec![1,2])); + assert_eq!(1, Solution::max_profit(vec![1, 2])); } } diff --git a/src/problem/p1227_airplane_seat_assignment_probability.rs b/src/problem/p1227_airplane_seat_assignment_probability.rs index 3f9343e..5d1b96b 100644 --- a/src/problem/p1227_airplane_seat_assignment_probability.rs +++ b/src/problem/p1227_airplane_seat_assignment_probability.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p123_best_time_to_buy_and_sell_stock_iii.rs b/src/problem/p123_best_time_to_buy_and_sell_stock_iii.rs index 0858fd8..5776c4f 100644 --- a/src/problem/p123_best_time_to_buy_and_sell_stock_iii.rs +++ b/src/problem/p123_best_time_to_buy_and_sell_stock_iii.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p124_binary_tree_maximum_path_sum.rs b/src/problem/p124_binary_tree_maximum_path_sum.rs index c7c5d82..05458f9 100644 --- a/src/problem/p124_binary_tree_maximum_path_sum.rs +++ b/src/problem/p124_binary_tree_maximum_path_sum.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,27 +25,29 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { fn max_sum(node: &Rc>, result: &mut i32) -> i32 { if node.borrow().left.is_none() && node.borrow().right.is_none() { *result = (*result).max(node.borrow().val); return node.borrow().val; - } + } let left_sum = if let Some(left) = &node.borrow().left { Self::max_sum(left, result) } else { 0 - }.max(0); + } + .max(0); let right_sum = if let Some(right) = &node.borrow().right { Self::max_sum(right, result) } else { 0 - }.max(0); + } + .max(0); *result = (*result).max(node.borrow().val + left_sum + right_sum); @@ -70,6 +72,5 @@ mod tests { use super::*; #[test] - fn test_124() { - } + fn test_124() {} } diff --git a/src/problem/p125_valid_palindrome.rs b/src/problem/p125_valid_palindrome.rs index 9994b55..c2d28eb 100644 --- a/src/problem/p125_valid_palindrome.rs +++ b/src/problem/p125_valid_palindrome.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -32,7 +31,7 @@ impl Solution { i += 1; j -= 1; } - + true } } @@ -45,7 +44,9 @@ mod tests { #[test] fn test_125() { - assert!(Solution::is_palindrome("A man, a plan, a canal: Panama".to_owned())); + assert!(Solution::is_palindrome( + "A man, a plan, a canal: Panama".to_owned() + )); assert!(!Solution::is_palindrome("0P".to_owned())); } } diff --git a/src/problem/p1261_find_elements_in_a_contaminated_binary_tree.rs b/src/problem/p1261_find_elements_in_a_contaminated_binary_tree.rs index 8ae235a..c78a902 100644 --- a/src/problem/p1261_find_elements_in_a_contaminated_binary_tree.rs +++ b/src/problem/p1261_find_elements_in_a_contaminated_binary_tree.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,18 +25,16 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::{collections::HashSet, collections::VecDeque, cell::RefCell, rc::Rc}; +use std::{cell::RefCell, collections::HashSet, collections::VecDeque, rc::Rc}; struct FindElements { - collected_set: HashSet + collected_set: HashSet, } - /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl FindElements { - fn new(root: Option>>) -> Self { let mut queue = VecDeque::new(); let mut collected_set = HashSet::new(); @@ -61,11 +59,9 @@ impl FindElements { }; } - FindElements { - collected_set - } + FindElements { collected_set } } - + fn find(&self, target: i32) -> bool { self.collected_set.contains(&target) } @@ -84,6 +80,5 @@ mod tests { use super::*; #[test] - fn test_1261() { - } + fn test_1261() {} } diff --git a/src/problem/p1276_number_of_burgers_with_no_waste_of_ingredients.rs b/src/problem/p1276_number_of_burgers_with_no_waste_of_ingredients.rs index 84aef71..3c9f6ab 100644 --- a/src/problem/p1276_number_of_burgers_with_no_waste_of_ingredients.rs +++ b/src/problem/p1276_number_of_burgers_with_no_waste_of_ingredients.rs @@ -2,36 +2,36 @@ * [1276] Number of Burgers with No Waste of Ingredients * * Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows: - * + * * Jumbo Burger: 4 tomato slices and 1 cheese slice. * Small Burger: 2 Tomato slices and 1 cheese slice. - * + * * Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return []. * * Example 1: - * + * * Input: tomatoSlices = 16, cheeseSlices = 7 * Output: [1,6] * Explantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese. * There will be no remaining ingredients. - * + * * Example 2: - * + * * Input: tomatoSlices = 17, cheeseSlices = 4 * Output: [] * Explantion: There will be no way to use all ingredients to make small and jumbo burgers. - * + * * Example 3: - * + * * Input: tomatoSlices = 4, cheeseSlices = 17 * Output: [] * Explantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining. - * + * * * Constraints: - * + * * 0 <= tomatoSlices, cheeseSlices <= 10^7 - * + * */ pub struct Solution {} @@ -42,15 +42,13 @@ pub struct Solution {} impl Solution { pub fn num_of_burgers(tomato_slices: i32, cheese_slices: i32) -> Vec { - let (mut tomato, mut cheese) = (tomato_slices as f32, - cheese_slices as f32); + let (mut tomato, mut cheese) = (tomato_slices as f32, cheese_slices as f32); if tomato == 0f32 && cheese == 0f32 { - return vec![0, 0] + return vec![0, 0]; } - if tomato == 0f32 || - tomato / cheese < 2f32 || tomato / cheese > 4f32 { - return vec![] + if tomato == 0f32 || tomato / cheese < 2f32 || tomato / cheese > 4f32 { + return vec![]; } let mut big_count = 0; @@ -65,10 +63,10 @@ impl Solution { } if tomato * cheese == 0f32 { - return vec![] + return vec![]; } } - + vec![big_count, cheese as i32] } } @@ -81,7 +79,7 @@ mod tests { #[test] fn test_1276() { - let empty_array : Vec = Vec::new(); + let empty_array: Vec = Vec::new(); assert_eq!(vec![1, 6], Solution::num_of_burgers(16, 7)); assert_eq!(empty_array, Solution::num_of_burgers(17, 4)); assert_eq!(empty_array, Solution::num_of_burgers(4, 17)); diff --git a/src/problem/p127_word_ladder.rs b/src/problem/p127_word_ladder.rs index db2de9e..d4c7832 100644 --- a/src/problem/p127_word_ladder.rs +++ b/src/problem/p127_word_ladder.rs @@ -19,7 +19,7 @@ impl Solution { start = i; break; } - } + } let mut neighbors = vec![HashSet::new(); word_list.len()]; @@ -51,44 +51,44 @@ impl Solution { // 如果开始和结束相同 // 则必然是跳了一步 if start == end { - return 2; + return 2; } let mut result = i32::MAX; // dijkstra算法 let mut distances = vec![i32::MAX; word_list.len()]; - let mut flags = vec![false; word_list.len()]; - distances[start] = 0; - flags[start] = true; - for &i in &neighbors[start] { - distances[i] = 1; - } + let mut flags = vec![false; word_list.len()]; + distances[start] = 0; + flags[start] = true; + for &i in &neighbors[start] { + distances[i] = 1; + } - for _ in 1..word_list.len() { - let mut min = i32::MAX; - let mut next = 0; + for _ in 1..word_list.len() { + let mut min = i32::MAX; + let mut next = 0; - for i in 0..word_list.len() { - if !flags[i] && distances[i] < min { - min = distances[i]; - next = i; - } - } - - flags[next] = true; - if next == end { - result = result.min(min); - break; - } - - for &i in &neighbors[next] { - if !flags[i] && min + 1 < distances[i] { - distances[i] = min + 1; - } + for i in 0..word_list.len() { + if !flags[i] && distances[i] < min { + min = distances[i]; + next = i; } } + flags[next] = true; + if next == end { + result = result.min(min); + break; + } + + for &i in &neighbors[next] { + if !flags[i] && min + 1 < distances[i] { + distances[i] = min + 1; + } + } + } + if result == i32::MAX { 0 } else { @@ -140,36 +140,43 @@ mod tests { ), 5 ); - - assert_eq!(Solution::ladder_length("a".to_owned(), "c".to_owned(), vec![ - "a".to_owned(), - "b".to_owned(), - "c".to_owned() - ]), 2); - - assert_eq!(Solution::ladder_length("a".to_owned(), "c".to_owned(), vec![ - "c".to_owned() - ]), 2); - + + assert_eq!( + Solution::ladder_length( + "a".to_owned(), + "c".to_owned(), + vec!["a".to_owned(), "b".to_owned(), "c".to_owned()] + ), + 2 + ); + + assert_eq!( + Solution::ladder_length("a".to_owned(), "c".to_owned(), vec!["c".to_owned()]), + 2 + ); + assert_eq!( Solution::ladder_length( "hot".to_owned(), "dog".to_owned(), - vec![ - "hot".to_owned(), - "dot".to_owned(), - "dog".to_owned(), - ] + vec!["hot".to_owned(), "dot".to_owned(), "dog".to_owned(),] ), 3 ); - assert_eq!(Solution::ladder_length("lost".to_owned(), "cost".to_owned(), vec![ - "most".to_owned(), - "fist".to_owned(), - "lost".to_owned(), - "cost".to_owned(), - "fish".to_owned() - ]), 2); + assert_eq!( + Solution::ladder_length( + "lost".to_owned(), + "cost".to_owned(), + vec![ + "most".to_owned(), + "fist".to_owned(), + "lost".to_owned(), + "cost".to_owned(), + "fish".to_owned() + ] + ), + 2 + ); } } diff --git a/src/problem/p129_sum_root_to_leaf_numbers.rs b/src/problem/p129_sum_root_to_leaf_numbers.rs index a58ee57..996bfc2 100644 --- a/src/problem/p129_sum_root_to_leaf_numbers.rs +++ b/src/problem/p129_sum_root_to_leaf_numbers.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,8 +25,8 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { fn dfs_sum(node: &Rc>, last_num: i32, result: &mut i32) { if node.borrow().left.is_none() && node.borrow().right.is_none() { @@ -42,7 +42,6 @@ impl Solution { } } - pub fn sum_numbers(root: Option>>) -> i32 { let mut result = 0; @@ -50,7 +49,6 @@ impl Solution { Self::dfs_sum(&root, 0, &mut result); } - result } } @@ -62,6 +60,5 @@ mod tests { use super::*; #[test] - fn test_129() { - } + fn test_129() {} } diff --git a/src/problem/p130_surrounded_regions.rs b/src/problem/p130_surrounded_regions.rs index 88d66f1..b369508 100644 --- a/src/problem/p130_surrounded_regions.rs +++ b/src/problem/p130_surrounded_regions.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -69,6 +68,5 @@ mod tests { use super::*; #[test] - fn test_130() { - } + fn test_130() {} } diff --git a/src/problem/p136_single_number.rs b/src/problem/p136_single_number.rs index 5c1e84c..736c116 100644 --- a/src/problem/p136_single_number.rs +++ b/src/problem/p136_single_number.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p137_single_number_ii.rs b/src/problem/p137_single_number_ii.rs index 859fe98..966261b 100644 --- a/src/problem/p137_single_number_ii.rs +++ b/src/problem/p137_single_number_ii.rs @@ -3,18 +3,17 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn single_number(nums: Vec) -> i32 { - let (mut a, mut b) = (0, 0); - + let (mut a, mut b) = (0, 0); + for i in nums { b = !a & (b ^ i); - a = !b & ( a ^ i); + a = !b & (a ^ i); } - + b } } diff --git a/src/problem/p139_word_break.rs b/src/problem/p139_word_break.rs index d00987b..e5944bf 100644 --- a/src/problem/p139_word_break.rs +++ b/src/problem/p139_word_break.rs @@ -3,9 +3,8 @@ */ pub struct Solution {} - // submission codes start here -use std::{rc::Rc, cell::RefCell, collections::HashMap}; +use std::{cell::RefCell, collections::HashMap, rc::Rc}; struct Trie { is_word: bool, @@ -80,9 +79,21 @@ mod tests { #[test] fn test_139() { - assert!(Solution::word_break("leetcode".to_owned(), vec_string!("leet", "code"))); - assert!(Solution::word_break("applepenapple".to_owned(), vec_string!("apple", "pen"))); - assert!(!Solution::word_break("catsandog".to_owned(), vec_string!("cats", "cat", "sand", "and", "cat"))); - assert!(Solution::word_break("aaaaaaa".to_owned(), vec_string!("aaa", "aaaa"))); + assert!(Solution::word_break( + "leetcode".to_owned(), + vec_string!("leet", "code") + )); + assert!(Solution::word_break( + "applepenapple".to_owned(), + vec_string!("apple", "pen") + )); + assert!(!Solution::word_break( + "catsandog".to_owned(), + vec_string!("cats", "cat", "sand", "and", "cat") + )); + assert!(Solution::word_break( + "aaaaaaa".to_owned(), + vec_string!("aaa", "aaaa") + )); } } diff --git a/src/problem/p1436_destination_city.rs b/src/problem/p1436_destination_city.rs index cdd339d..5fc83fd 100644 --- a/src/problem/p1436_destination_city.rs +++ b/src/problem/p1436_destination_city.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -19,7 +18,12 @@ impl Solution { out_map.entry(&path[1]).or_insert(0); } - out_map.iter().filter(|(_, &v)| v == 0).map(|(k, _)| k.to_string()).next().unwrap() + out_map + .iter() + .filter(|(_, &v)| v == 0) + .map(|(k, _)| k.to_string()) + .next() + .unwrap() } } @@ -31,6 +35,13 @@ mod tests { #[test] fn test_1436() { - assert_eq!("A".to_owned(), Solution::dest_city(vec![vec_string!("B", "C"), vec_string!("D", "B"), vec_string!("C", "A")])); + assert_eq!( + "A".to_owned(), + Solution::dest_city(vec![ + vec_string!("B", "C"), + vec_string!("D", "B"), + vec_string!("C", "A") + ]) + ); } } diff --git a/src/problem/p144_binary_tree_preorder_traversal.rs b/src/problem/p144_binary_tree_preorder_traversal.rs index 8de67a4..19637eb 100644 --- a/src/problem/p144_binary_tree_preorder_traversal.rs +++ b/src/problem/p144_binary_tree_preorder_traversal.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,8 +25,8 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn preorder_traversal(root: Option>>) -> Vec { let mut result = Vec::new(); @@ -56,7 +56,9 @@ mod tests { #[test] fn test_144() { - assert_eq!(Solution::preorder_traversal(to_tree( - vec![Some(1), None, Some(2), Some(3)])), vec![1,2,3]); + assert_eq!( + Solution::preorder_traversal(to_tree(vec![Some(1), None, Some(2), Some(3)])), + vec![1, 2, 3] + ); } } diff --git a/src/problem/p1450_number_of_students_doing_homework_at_a_given_time.rs b/src/problem/p1450_number_of_students_doing_homework_at_a_given_time.rs index 6797057..3c35c88 100644 --- a/src/problem/p1450_number_of_students_doing_homework_at_a_given_time.rs +++ b/src/problem/p1450_number_of_students_doing_homework_at_a_given_time.rs @@ -3,30 +3,25 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn busy_student(start_time: Vec, end_time: Vec, query_time: i32) -> i32 { - let start_pos = start_time.iter().enumerate().filter_map( - |(pos, &value)| { - if value <= query_time { - Some(pos) - } else { - None - } + let start_pos = start_time.iter().enumerate().filter_map(|(pos, &value)| { + if value <= query_time { + Some(pos) + } else { + None } - ); + }); - let pos = start_pos.filter_map( - |pos| { - if end_time[pos] >= query_time { - Some(pos) - } else { - None - } + let pos = start_pos.filter_map(|pos| { + if end_time[pos] >= query_time { + Some(pos) + } else { + None } - ); + }); pos.count() as i32 } diff --git a/src/problem/p145_binary_tree_postorder_traversal.rs b/src/problem/p145_binary_tree_postorder_traversal.rs index 4dad7da..3dbd754 100644 --- a/src/problem/p145_binary_tree_postorder_traversal.rs +++ b/src/problem/p145_binary_tree_postorder_traversal.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,8 +25,8 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn postorder_traversal(root: Option>>) -> Vec { let mut result = Vec::new(); @@ -65,11 +65,13 @@ mod tests { #[test] fn test_145() { - assert_eq!(Solution::postorder_traversal( - to_tree(vec![Some(1), None, Some(2), Some(3)])), - vec![3,2,1]); - assert_eq!(Solution::postorder_traversal( - to_tree(vec![Some(2), None, Some(3), None, Some(1)]) - ), vec![1,3,2]); + assert_eq!( + Solution::postorder_traversal(to_tree(vec![Some(1), None, Some(2), Some(3)])), + vec![3, 2, 1] + ); + assert_eq!( + Solution::postorder_traversal(to_tree(vec![Some(2), None, Some(3), None, Some(1)])), + vec![1, 3, 2] + ); } } diff --git a/src/problem/p149_max_points_on_a_line.rs b/src/problem/p149_max_points_on_a_line.rs index ca2506a..125e950 100644 --- a/src/problem/p149_max_points_on_a_line.rs +++ b/src/problem/p149_max_points_on_a_line.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -33,10 +32,7 @@ impl Slope { y /= gcd; } - Self { - x, - y, - } + Self { x, y } } fn gcd(a: i32, b: i32) -> i32 { @@ -60,20 +56,20 @@ impl Solution { if result > n - i || result > n / 2 { break; } - + let mut map = HashMap::new(); - for j in i+1..n { + for j in i + 1..n { let slope = Slope::new(&points[i], &points[j]); - + let entry = map.entry(slope).or_insert(0); *entry += 1; } - + let mut max = 0; for i in map.values() { max = max.max(*i); } - + result = result.max(max + 1); } diff --git a/src/problem/p150_evaluate_reverse_polish_notation.rs b/src/problem/p150_evaluate_reverse_polish_notation.rs index afedb06..2b0a9b6 100644 --- a/src/problem/p150_evaluate_reverse_polish_notation.rs +++ b/src/problem/p150_evaluate_reverse_polish_notation.rs @@ -21,7 +21,7 @@ impl Solution { "-" => stack.push(first - second), "*" => stack.push(first * second), "/" => stack.push(first / second), - _ => {}, + _ => {} } } } @@ -38,6 +38,6 @@ mod tests { #[test] fn test_150() { - assert_eq!(9, Solution::eval_rpn(vec_string!["2","1","+","3","*"])); + assert_eq!(9, Solution::eval_rpn(vec_string!["2", "1", "+", "3", "*"])); } } diff --git a/src/problem/p151_reverse_words_in_a_string.rs b/src/problem/p151_reverse_words_in_a_string.rs index fd5d83a..4ec4f30 100644 --- a/src/problem/p151_reverse_words_in_a_string.rs +++ b/src/problem/p151_reverse_words_in_a_string.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -15,7 +14,7 @@ impl Solution { words.push(word); } } - + let length = words.len(); let mut result = String::from(words[length - 1]); @@ -36,6 +35,9 @@ mod tests { #[test] fn test_151() { - assert_eq!("blue is sky the".to_owned(), Solution::reverse_words("the sky is blue".to_owned())); + assert_eq!( + "blue is sky the".to_owned(), + Solution::reverse_words("the sky is blue".to_owned()) + ); } } diff --git a/src/problem/p153_find_minimum_in_rotated_sorted_array.rs b/src/problem/p153_find_minimum_in_rotated_sorted_array.rs index 4d7e38b..ed55a49 100644 --- a/src/problem/p153_find_minimum_in_rotated_sorted_array.rs +++ b/src/problem/p153_find_minimum_in_rotated_sorted_array.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -32,6 +31,5 @@ mod tests { use super::*; #[test] - fn test_153() { - } + fn test_153() {} } diff --git a/src/problem/p155_min_stack.rs b/src/problem/p155_min_stack.rs index 85cc924..e113eaf 100644 --- a/src/problem/p155_min_stack.rs +++ b/src/problem/p155_min_stack.rs @@ -3,46 +3,43 @@ */ pub struct Solution {} - // submission codes start here use std::{cmp::Reverse, collections::BinaryHeap}; struct MinStack { - heap : BinaryHeap>, - stack: Vec + heap: BinaryHeap>, + stack: Vec, } - /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl MinStack { - fn new() -> Self { MinStack { heap: BinaryHeap::new(), - stack: vec![] + stack: vec![], } } - + fn push(&mut self, val: i32) { self.heap.push(Reverse(val)); self.stack.push(val); } - + fn pop(&mut self) { let n = self.stack.pop().unwrap_or(0); if !self.stack.contains(&n) { self.heap.retain(|i| i.0 != n); - } + } } - + fn top(&self) -> i32 { *self.stack.last().unwrap_or(&0) } - + fn get_min(&self) -> i32 { self.heap.peek().unwrap_or(&Reverse(0)).0 } @@ -64,6 +61,5 @@ mod tests { use super::*; #[test] - fn test_155() { - } + fn test_155() {} } diff --git a/src/problem/p162_find_peak_element.rs b/src/problem/p162_find_peak_element.rs index 42d2a1c..f7d0d3f 100644 --- a/src/problem/p162_find_peak_element.rs +++ b/src/problem/p162_find_peak_element.rs @@ -7,22 +7,22 @@ * You must write an algorithm that runs in O(log n) time. * * 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: 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. * * Constraints: - * + * * 1 <= nums.length <= 1000 * -2^31 <= nums[i] <= 2^31 - 1 * nums[i] != nums[i + 1] for all valid i. - * + * */ pub struct Solution {} @@ -53,7 +53,7 @@ impl Solution { let mid = (left + right) / 2; if compare(mid) { - return mid as i32 + return mid as i32; } if nums[mid] < nums[mid + 1] { @@ -75,8 +75,8 @@ mod tests { #[test] fn test_162() { - assert_eq!(2, Solution::find_peak_element(vec![1,2,3,1])); - assert_eq!(5, Solution::find_peak_element(vec![1,2,1,3,5,6,4])); - assert_eq!(1, Solution::find_peak_element(vec![1,2])); + assert_eq!(2, Solution::find_peak_element(vec![1, 2, 3, 1])); + assert_eq!(5, Solution::find_peak_element(vec![1, 2, 1, 3, 5, 6, 4])); + assert_eq!(1, Solution::find_peak_element(vec![1, 2])); } } diff --git a/src/problem/p167_two_sum_ii_input_array_is_sorted.rs b/src/problem/p167_two_sum_ii_input_array_is_sorted.rs index 31a02a1..3ce0011 100644 --- a/src/problem/p167_two_sum_ii_input_array_is_sorted.rs +++ b/src/problem/p167_two_sum_ii_input_array_is_sorted.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -16,17 +15,14 @@ impl Solution { if sum == target { break; - } - else if sum < target { + } else if sum < target { i += 1; - } - else { + } else { j -= 1; } - } - vec![(i + 1) as i32 , (j + 1) as i32] + vec![(i + 1) as i32, (j + 1) as i32] } } @@ -38,6 +34,6 @@ mod tests { #[test] fn test_167() { - assert_eq!(vec![1,2], Solution::two_sum(vec![2,7,11,15], 9)); + assert_eq!(vec![1, 2], Solution::two_sum(vec![2, 7, 11, 15], 9)); } } diff --git a/src/problem/p1686_stone_game_vi.rs b/src/problem/p1686_stone_game_vi.rs index 48ac909..fdac208 100644 --- a/src/problem/p1686_stone_game_vi.rs +++ b/src/problem/p1686_stone_game_vi.rs @@ -3,37 +3,30 @@ */ pub struct Solution {} - // submission codes start here struct Stone { sum: i32, alice: i32, - bob: i32 + bob: i32, } impl Solution { pub fn stone_game_vi(alice_values: Vec, bob_values: Vec) -> i32 { - let mut stones: Vec = alice_values.iter() + let mut stones: Vec = alice_values + .iter() .zip(bob_values.iter()) - .map(|(a,b)| Stone { + .map(|(a, b)| Stone { sum: *a + *b, alice: *a, - bob: *b + bob: *b, }) .collect(); stones.sort_unstable_by(|a, b| b.sum.cmp(&a.sum)); - let alice_sum: i32 = stones.iter() - .step_by(2) - .map(|s| s.alice) - .sum(); - let bob_sum: i32 = stones.iter() - .skip(1) - .step_by(2) - .map(|s| s.bob) - .sum(); + let alice_sum: i32 = stones.iter().step_by(2).map(|s| s.alice).sum(); + let bob_sum: i32 = stones.iter().skip(1).step_by(2).map(|s| s.bob).sum(); if alice_sum > bob_sum { 1 @@ -53,6 +46,6 @@ mod tests { #[test] fn test_1686() { - assert_eq!(Solution::stone_game_vi(vec![1,3], vec![2,1]), 1); + assert_eq!(Solution::stone_game_vi(vec![1, 3], vec![2, 1]), 1); } } diff --git a/src/problem/p1690_stone_game_vii.rs b/src/problem/p1690_stone_game_vii.rs index 24dc181..a64d42d 100644 --- a/src/problem/p1690_stone_game_vii.rs +++ b/src/problem/p1690_stone_game_vii.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -15,13 +14,12 @@ impl Solution { sum[index + 1] = sum[index] + *value; } - let mut dp = vec![vec![0;n];n]; + let mut dp = vec![vec![0; n]; n]; - for i in (0..=n-2).rev() { - for j in i+1..n { - dp[i][j] = (sum[j + 1] - sum[i + 1] - dp[i + 1][j]).max( - sum[j] - sum[i] - dp[i][j - 1] - ); + for i in (0..=n - 2).rev() { + for j in i + 1..n { + dp[i][j] = + (sum[j + 1] - sum[i + 1] - dp[i + 1][j]).max(sum[j] - sum[i] - dp[i][j - 1]); } } @@ -37,6 +35,6 @@ mod tests { #[test] fn test_1690() { - assert_eq!(Solution::stone_game_vii(vec![5,3,1,4,2]), 6); + assert_eq!(Solution::stone_game_vii(vec![5, 3, 1, 4, 2]), 6); } } diff --git a/src/problem/p1696_jump_game_vi.rs b/src/problem/p1696_jump_game_vi.rs index f070714..854dc7d 100644 --- a/src/problem/p1696_jump_game_vi.rs +++ b/src/problem/p1696_jump_game_vi.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::VecDeque; @@ -12,7 +11,7 @@ impl Solution { pub fn max_result(nums: Vec, k: i32) -> i32 { let n = nums.len(); let k = k as usize; - let mut dp = vec![0;n]; + let mut dp = vec![0; n]; let mut queue = VecDeque::new(); dp[0] = nums[0]; @@ -50,8 +49,11 @@ mod tests { #[test] fn test_1696() { - assert_eq!(Solution::max_result(vec![1,-1,-2,4,-7,3], 2), 7); - assert_eq!(Solution::max_result(vec![10,-5,-2,4,0,3], 3), 17); - assert_eq!(Solution::max_result(vec![1,-5,-20,4,-1,3,-6,-3], 2), 0); + assert_eq!(Solution::max_result(vec![1, -1, -2, 4, -7, 3], 2), 7); + assert_eq!(Solution::max_result(vec![10, -5, -2, 4, 0, 3], 3), 17); + assert_eq!( + Solution::max_result(vec![1, -5, -20, 4, -1, 3, -6, -3], 2), + 0 + ); } } diff --git a/src/problem/p169_majority_element.rs b/src/problem/p169_majority_element.rs index 7798e0a..3bb306d 100644 --- a/src/problem/p169_majority_element.rs +++ b/src/problem/p169_majority_element.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -16,11 +15,7 @@ impl Solution { candidate = i; } - count += if candidate == i { - 1 - } else { - -1 - }; + count += if candidate == i { 1 } else { -1 }; } candidate @@ -35,6 +30,6 @@ mod tests { #[test] fn test_169() { - assert_eq!(3, Solution::majority_element(vec![3,2,3])); + assert_eq!(3, Solution::majority_element(vec![3, 2, 3])); } } diff --git a/src/problem/p172_factorial_trailing_zeroes.rs b/src/problem/p172_factorial_trailing_zeroes.rs index 8adb62d..6620d20 100644 --- a/src/problem/p172_factorial_trailing_zeroes.rs +++ b/src/problem/p172_factorial_trailing_zeroes.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -15,7 +14,7 @@ impl Solution { n /= 5; result += n; } - + result } } @@ -27,6 +26,5 @@ mod tests { use super::*; #[test] - fn test_172() { - } + fn test_172() {} } diff --git a/src/problem/p173_binary_search_tree_iterator.rs b/src/problem/p173_binary_search_tree_iterator.rs index a4428db..1d03821 100644 --- a/src/problem/p173_binary_search_tree_iterator.rs +++ b/src/problem/p173_binary_search_tree_iterator.rs @@ -5,7 +5,7 @@ pub struct Solution {} use tokio::time::error::Elapsed; -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -28,11 +28,11 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; struct BSTIterator { - stack: Vec>> + stack: Vec>>, } /** @@ -40,13 +40,10 @@ struct BSTIterator { * If you need a mutable reference, change it to `&mut self` instead. */ impl BSTIterator { - fn new(root: Option>>) -> Self { if root.is_none() { - return BSTIterator { - stack: vec![] - }; - } + return BSTIterator { stack: vec![] }; + } let mut stack = vec![]; let root = root.unwrap(); @@ -64,16 +61,13 @@ impl BSTIterator { node = left; } - - BSTIterator { - stack - } + BSTIterator { stack } } - + fn next(&mut self) -> i32 { let node = self.stack.pop().unwrap(); let val = node.borrow().val; - + if let Some(right) = &node.borrow().right { let mut node = Rc::clone(right); @@ -92,7 +86,7 @@ impl BSTIterator { val } - + fn has_next(&self) -> bool { !self.stack.is_empty() } @@ -112,6 +106,5 @@ mod tests { use super::*; #[test] - fn test_173() { - } + fn test_173() {} } diff --git a/src/problem/p1793_maximum_score_of_a_good_subarray.rs b/src/problem/p1793_maximum_score_of_a_good_subarray.rs index 09b6754..d09e306 100644 --- a/src/problem/p1793_maximum_score_of_a_good_subarray.rs +++ b/src/problem/p1793_maximum_score_of_a_good_subarray.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -43,6 +42,6 @@ mod tests { #[test] fn test_1793() { - assert_eq!(15, Solution::maximum_score(vec![1,4,3,7,4,5], 3)); + assert_eq!(15, Solution::maximum_score(vec![1, 4, 3, 7, 4, 5], 3)); } } diff --git a/src/problem/p17_letter_combinations_of_a_phone_number.rs b/src/problem/p17_letter_combinations_of_a_phone_number.rs index c1874ce..d0ff73f 100644 --- a/src/problem/p17_letter_combinations_of_a_phone_number.rs +++ b/src/problem/p17_letter_combinations_of_a_phone_number.rs @@ -3,17 +3,17 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn letter_combinations(digits: String) -> Vec { let mut result = vec![]; - let digits: Vec = digits.chars() + let digits: Vec = digits + .chars() .map(|c| (c.to_digit(10).unwrap() - 2) as usize) .collect(); let mut str = Vec::with_capacity(digits.len()); - + Self::search(&digits, &mut str, &mut result, 0); result @@ -37,7 +37,7 @@ impl Solution { } return; } - + for &c in &map[digits[pos]] { str.push(c); Self::search(digits, str, result, pos + 1); diff --git a/src/problem/p1845_seat_reservation_manager.rs b/src/problem/p1845_seat_reservation_manager.rs index acb1513..0980f4a 100644 --- a/src/problem/p1845_seat_reservation_manager.rs +++ b/src/problem/p1845_seat_reservation_manager.rs @@ -4,11 +4,11 @@ pub struct Solution {} // submission codes start here -use std::collections::BinaryHeap; use std::cmp::Reverse; +use std::collections::BinaryHeap; struct SeatManager { - seats: BinaryHeap> + seats: BinaryHeap>, } /** @@ -16,24 +16,21 @@ struct SeatManager { * If you need a mutable reference, change it to `&mut self` instead. */ impl SeatManager { - fn new(n: i32) -> Self { let mut heap = BinaryHeap::with_capacity(n as usize); - + for i in 1..=n { heap.push(Reverse(i)); } - - Self { - seats: heap - } + + Self { seats: heap } } - + fn reserve(&mut self) -> i32 { let head = self.seats.pop(); head.unwrap().0 } - + fn unreserve(&mut self, seat_number: i32) { self.seats.push(Reverse(seat_number)); } @@ -55,7 +52,7 @@ mod tests { #[test] fn test_1845() { let mut manager = SeatManager::new(5); - + assert_eq!(1, manager.reserve()); } } diff --git a/src/problem/p1870_minimum_speed_to_arrive_on_time.rs b/src/problem/p1870_minimum_speed_to_arrive_on_time.rs index 8bdf594..3ad6fec 100644 --- a/src/problem/p1870_minimum_speed_to_arrive_on_time.rs +++ b/src/problem/p1870_minimum_speed_to_arrive_on_time.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -14,9 +13,8 @@ impl Solution { return -1; } - let max_speed = (*dist.iter().max().unwrap()).max( - ((dist[n - 1] as f64) / (hour - (n - 1) as f64)).ceil() as i32 - ); + let max_speed = (*dist.iter().max().unwrap()) + .max(((dist[n - 1] as f64) / (hour - (n - 1) as f64)).ceil() as i32); let check = |v: i32| -> bool { let mut time = 0; @@ -58,7 +56,10 @@ mod tests { #[test] fn test_1870() { assert_eq!(-1, Solution::min_speed_on_time(vec![1, 1], 1.0)); - assert_eq!(10_000_000, Solution::min_speed_on_time(vec![1, 1, 100_000], 2.01)); + assert_eq!( + 10_000_000, + Solution::min_speed_on_time(vec![1, 1, 100_000], 2.01) + ); assert_eq!(1, Solution::min_speed_on_time(vec![1, 3, 2], 6f64)); assert_eq!(3, Solution::min_speed_on_time(vec![1, 3, 2], 2.7)); assert_eq!(-1, Solution::min_speed_on_time(vec![1, 3, 2], 1.9)); diff --git a/src/problem/p1884_egg_drop_with_2_eggs_and_n_floors.rs b/src/problem/p1884_egg_drop_with_2_eggs_and_n_floors.rs index b84e690..40bda12 100644 --- a/src/problem/p1884_egg_drop_with_2_eggs_and_n_floors.rs +++ b/src/problem/p1884_egg_drop_with_2_eggs_and_n_floors.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p188_best_time_to_buy_and_sell_stock_iv.rs b/src/problem/p188_best_time_to_buy_and_sell_stock_iv.rs index 01291d8..c4b697d 100644 --- a/src/problem/p188_best_time_to_buy_and_sell_stock_iv.rs +++ b/src/problem/p188_best_time_to_buy_and_sell_stock_iv.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p190_reverse_bits.rs b/src/problem/p190_reverse_bits.rs index 2ec39bb..13c8a2e 100644 --- a/src/problem/p190_reverse_bits.rs +++ b/src/problem/p190_reverse_bits.rs @@ -3,12 +3,11 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn reverse_bits(x: u32) -> u32 { - x.reverse_bits() + x.reverse_bits() } } @@ -19,6 +18,5 @@ mod tests { use super::*; #[test] - fn test_190() { - } + fn test_190() {} } diff --git a/src/problem/p191_number_of_1_bits.rs b/src/problem/p191_number_of_1_bits.rs index 390e5a0..091510f 100644 --- a/src/problem/p191_number_of_1_bits.rs +++ b/src/problem/p191_number_of_1_bits.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -39,17 +38,17 @@ impl Solution { 1 << 3, 1 << 2, 1 << 1, - 1 + 1, ]; - + let mut result = 0; - + for i in 0..31 { if n & ARRAY[i] == ARRAY[i] { result += 1; } } - + result } } diff --git a/src/problem/p1928_minimum_cost_to_reach_destination_in_time.rs b/src/problem/p1928_minimum_cost_to_reach_destination_in_time.rs index 34eacb3..71ec671 100644 --- a/src/problem/p1928_minimum_cost_to_reach_destination_in_time.rs +++ b/src/problem/p1928_minimum_cost_to_reach_destination_in_time.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -12,7 +11,7 @@ impl Solution { let max_time = max_time as usize; let max_value = i32::MAX / 2; - let mut dp = vec![vec![max_value;n];max_time + 1]; + let mut dp = vec![vec![max_value; n]; max_time + 1]; dp[0][0] = passing_fees[0]; @@ -26,7 +25,7 @@ impl Solution { } } } - + let mut result = max_value; for t in 1..=max_time { @@ -38,7 +37,7 @@ impl Solution { } else { result } - } + } } // submission codes end @@ -48,7 +47,5 @@ mod tests { use super::*; #[test] - fn test_1928() { - - } + fn test_1928() {} } diff --git a/src/problem/p1969_minimum_non_zero_product_of_the_array_elements.rs b/src/problem/p1969_minimum_non_zero_product_of_the_array_elements.rs index bebf9d9..09f5cf4 100644 --- a/src/problem/p1969_minimum_non_zero_product_of_the_array_elements.rs +++ b/src/problem/p1969_minimum_non_zero_product_of_the_array_elements.rs @@ -5,7 +5,6 @@ use std::convert::TryInto; */ pub struct Solution {} - // submission codes start here impl Solution { @@ -13,14 +12,16 @@ impl Solution { let p = p as i64; if p == 1 { return 1; - } + } let m = 1e9 as i64 + 7; let x = Solution::fast_power(2, p, m) - 1; let y = 1 << (p - 1); dbg!(x, y); - return (Solution::fast_power(x - 1, y - 1, m) * x % m).try_into().unwrap(); + return (Solution::fast_power(x - 1, y - 1, m) * x % m) + .try_into() + .unwrap(); } fn fast_power(x: i64, n: i64, m: i64) -> i64 { diff --git a/src/problem/p1976_number_of_ways_to_arrive_at_destination.rs b/src/problem/p1976_number_of_ways_to_arrive_at_destination.rs index ee3b8f1..af378de 100644 --- a/src/problem/p1976_number_of_ways_to_arrive_at_destination.rs +++ b/src/problem/p1976_number_of_ways_to_arrive_at_destination.rs @@ -3,14 +3,13 @@ */ pub struct Solution {} - // submission codes start here use std::collections::BinaryHeap; #[derive(PartialEq, Eq)] struct Node { node: usize, - distance: i64 + distance: i64, } impl PartialOrd for Node { @@ -29,8 +28,8 @@ impl Solution { pub fn count_paths(n: i32, roads: Vec>) -> i32 { let m = 1e9 as i32 + 7; let n = n as usize; - let mut graph = vec![vec![];n]; - + let mut graph = vec![vec![]; n]; + for road in roads { let x = road[0] as usize; let y = road[1] as usize; @@ -40,17 +39,20 @@ impl Solution { graph[y].push((x, t)); } - let mut distance = vec![i64::MAX;n]; + let mut distance = vec![i64::MAX; n]; distance[0] = 0; - let mut ways = vec![0;n]; + let mut ways = vec![0; n]; ways[0] = 1; let mut queue = BinaryHeap::new(); - queue.push(Node {node: 0, distance: 0}); + queue.push(Node { + node: 0, + distance: 0, + }); while !queue.is_empty() { let now = queue.pop().unwrap(); - + if now.distance > distance[now.node] { continue; } @@ -60,7 +62,10 @@ impl Solution { distance[next.0] = now.distance + next.1; ways[next.0] = ways[now.node]; - queue.push(Node {node: next.0, distance: now.distance + next.1}); + queue.push(Node { + node: next.0, + distance: now.distance + next.1, + }); } else if now.distance + next.1 == distance[next.0] { ways[next.0] = (ways[now.node] + ways[next.0]) % m; } @@ -78,7 +83,5 @@ mod tests { use super::*; #[test] - fn test_1976() { - - } + fn test_1976() {} } diff --git a/src/problem/p198_house_robber.rs b/src/problem/p198_house_robber.rs index c0f3647..4f8bed8 100644 --- a/src/problem/p198_house_robber.rs +++ b/src/problem/p198_house_robber.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p1997_first_day_where_you_have_been_in_all_the_rooms.rs b/src/problem/p1997_first_day_where_you_have_been_in_all_the_rooms.rs index 6aec029..febfb5d 100644 --- a/src/problem/p1997_first_day_where_you_have_been_in_all_the_rooms.rs +++ b/src/problem/p1997_first_day_where_you_have_been_in_all_the_rooms.rs @@ -3,13 +3,12 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn first_day_been_in_all_rooms(next_visit: Vec) -> i32 { let m = 1_000_000_007; - let mut dp = vec![0;next_visit.len()]; + let mut dp = vec![0; next_visit.len()]; dp[0] = 2; for i in 1..next_visit.len() { @@ -34,6 +33,5 @@ mod tests { use super::*; #[test] - fn test_1997() { - } + fn test_1997() {} } diff --git a/src/problem/p199_binary_tree_right_side_view.rs b/src/problem/p199_binary_tree_right_side_view.rs index e168e87..f79d89d 100644 --- a/src/problem/p199_binary_tree_right_side_view.rs +++ b/src/problem/p199_binary_tree_right_side_view.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,9 +25,9 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -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 result = vec![]; @@ -68,6 +68,5 @@ mod tests { use super::*; #[test] - fn test_199() { - } + fn test_199() {} } diff --git a/src/problem/p1_two_sum.rs b/src/problem/p1_two_sum.rs index bf5203c..d23ea15 100644 --- a/src/problem/p1_two_sum.rs +++ b/src/problem/p1_two_sum.rs @@ -6,29 +6,29 @@ * You can return the answer in any order. * * Example 1: - * + * * Input: nums = [2,7,11,15], target = 9 * Output: [0,1] * Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. - * + * * Example 2: - * + * * Input: nums = [3,2,4], target = 6 * Output: [1,2] - * + * * Example 3: - * + * * Input: nums = [3,3], target = 6 * Output: [0,1] - * + * * * Constraints: - * + * * 2 <= nums.length <= 10^4 * -10^9 <= nums[i] <= 10^9 * -10^9 <= target <= 10^9 * Only one valid answer exists. - * + * * * Follow-up: Can you come up with an algorithm that is less than O(n^2) time complexity? */ diff --git a/src/problem/p200_number_of_islands.rs b/src/problem/p200_number_of_islands.rs index 58bd113..44ab8af 100644 --- a/src/problem/p200_number_of_islands.rs +++ b/src/problem/p200_number_of_islands.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -41,7 +40,7 @@ impl Solution { if grid[i][j] == '1' { result += 1; Self::dfs(&mut grid, i as i32, j as i32); - } + } } } @@ -56,6 +55,5 @@ mod tests { use super::*; #[test] - fn test_200() { - } + fn test_200() {} } diff --git a/src/problem/p201_bitwise_and_of_numbers_range.rs b/src/problem/p201_bitwise_and_of_numbers_range.rs index 8604aef..e25ee2b 100644 --- a/src/problem/p201_bitwise_and_of_numbers_range.rs +++ b/src/problem/p201_bitwise_and_of_numbers_range.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -13,7 +12,7 @@ impl Solution { while left < right { right = right & (right - 1); } - + right } } diff --git a/src/problem/p2024_maximize_the_confusion_of_an_exam.rs b/src/problem/p2024_maximize_the_confusion_of_an_exam.rs index 11d97f0..dee04ce 100644 --- a/src/problem/p2024_maximize_the_confusion_of_an_exam.rs +++ b/src/problem/p2024_maximize_the_confusion_of_an_exam.rs @@ -3,38 +3,37 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn max_consecutive_answers(answer_key: String, k: i32) -> i32 { - let str : Vec = answer_key.chars().collect(); - + let str: Vec = answer_key.chars().collect(); + Self::max_consecutive_char(&str, k, 'T').max(Self::max_consecutive_char(&str, k, 'F')) } - - fn max_consecutive_char(str: &Vec, k: i32, c : char) -> i32 { + + fn max_consecutive_char(str: &Vec, k: i32, c: char) -> i32 { let n = str.len(); let mut result = 0; - + let (mut left, mut sum) = (0, 0); for right in 0..n { sum += match str[right] == c { true => 0, - false => 1 + false => 1, }; while sum > k { sum -= match str[left] == c { true => 0, - false => 1 + false => 1, }; left += 1; } - + result = result.max(right - left + 1); } - + result as i32 } } diff --git a/src/problem/p205_isomorphic_strings.rs b/src/problem/p205_isomorphic_strings.rs index e72e657..3bcb9a4 100644 --- a/src/problem/p205_isomorphic_strings.rs +++ b/src/problem/p205_isomorphic_strings.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -37,6 +36,5 @@ mod tests { use super::*; #[test] - fn test_205() { - } + fn test_205() {} } diff --git a/src/problem/p2073_time_needed_to_buy_tickets.rs b/src/problem/p2073_time_needed_to_buy_tickets.rs index 2d056a9..441e476 100644 --- a/src/problem/p2073_time_needed_to_buy_tickets.rs +++ b/src/problem/p2073_time_needed_to_buy_tickets.rs @@ -3,39 +3,34 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn time_required_to_buy(tickets: Vec, k: i32) -> i32 { use std::collections::VecDeque; let k = k as usize; - + let mut queue = VecDeque::with_capacity(tickets.len()); for (i, &v) in tickets.iter().enumerate() { - queue.push_back(if i == k { - (v, true) - } else { - (v, false) - }); + queue.push_back(if i == k { (v, true) } else { (v, false) }); } - + let mut second = 0; loop { let head = queue.pop_front().unwrap(); second += 1; - + if head.0 == 1 { // 卖完了 if head.1 { break; } - } else { + } else { queue.push_back((head.0 - 1, head.1)); } } - + second } } @@ -48,7 +43,7 @@ mod tests { #[test] fn test_2073() { - assert_eq!(6, Solution::time_required_to_buy(vec![2,3,2], 2)); - assert_eq!(8, Solution::time_required_to_buy(vec![5,1,1,1], 0)); + assert_eq!(6, Solution::time_required_to_buy(vec![2, 3, 2], 2)); + assert_eq!(8, Solution::time_required_to_buy(vec![5, 1, 1, 1], 0)); } } diff --git a/src/problem/p207_course_schedule.rs b/src/problem/p207_course_schedule.rs index 6a107c8..95b0bc6 100644 --- a/src/problem/p207_course_schedule.rs +++ b/src/problem/p207_course_schedule.rs @@ -3,15 +3,14 @@ */ pub struct Solution {} - // submission codes start here use std::collections::VecDeque; impl Solution { pub fn can_finish(num_courses: i32, prerequisites: Vec>) -> bool { let num_courses = num_courses as usize; - let mut edges = vec![vec![];num_courses]; - let mut in_degs = vec![0;num_courses]; + let mut edges = vec![vec![]; num_courses]; + let mut in_degs = vec![0; num_courses]; for edge in prerequisites { edges[edge[1] as usize].push(edge[0] as usize); @@ -24,20 +23,20 @@ impl Solution { if in_degs[i] == 0 { queue.push_back(i); } - } + } let mut visited = 0; while !queue.is_empty() { - let node = queue.pop_front().unwrap(); + let node = queue.pop_front().unwrap(); visited += 1; for next_node in &edges[node] { in_degs[*next_node] -= 1; - + if in_degs[*next_node] == 0 { queue.push_back(*next_node); } - } + } } visited == num_courses @@ -51,6 +50,5 @@ mod tests { use super::*; #[test] - fn test_207() { - } + fn test_207() {} } diff --git a/src/problem/p2085_count_common_words_with_one_occurrence.rs b/src/problem/p2085_count_common_words_with_one_occurrence.rs index 1d3ee2d..5915875 100644 --- a/src/problem/p2085_count_common_words_with_one_occurrence.rs +++ b/src/problem/p2085_count_common_words_with_one_occurrence.rs @@ -4,7 +4,7 @@ * Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays. * * Example 1: - * + * * Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"] * Output: 2 * Explanation: @@ -13,26 +13,26 @@ * - "is" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string. * - "as" appears once in words1, but does not appear in words2. We do not count this string. * Thus, there are 2 strings that appear exactly once in each of the two arrays. - * + * * Example 2: - * + * * Input: words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"] * Output: 0 * Explanation: There are no strings that appear in each of the two arrays. - * + * * Example 3: - * + * * Input: words1 = ["a","ab"], words2 = ["a","a","a","ab"] * Output: 1 * Explanation: The only string that appears exactly once in each of the two arrays is "ab". - * + * * * Constraints: - * + * * 1 <= words1.length, words2.length <= 1000 * 1 <= words1[i].length, words2[j].length <= 30 * words1[i] and words2[j] consists only of lowercase English letters. - * + * */ pub struct Solution {} @@ -50,9 +50,10 @@ impl Solution { for i in &words1 { match dict.get(i) { None => { - dict.insert(i, 0);} + dict.insert(i, 0); + } Some(_) => { - dict.insert(i ,1); + dict.insert(i, 1); } } } @@ -63,14 +64,14 @@ impl Solution { Some(value) => { if *value == 0 { dict.insert(i, 2); - } else if *value == 2{ + } else if *value == 2 { dict.insert(i, 1); } } } } - dict.values().filter(|x| {**x == 2}).count() as i32 + dict.values().filter(|x| **x == 2).count() as i32 } } @@ -81,6 +82,5 @@ mod tests { use super::*; #[test] - fn test_2085() { - } + fn test_2085() {} } diff --git a/src/problem/p209_minimum_size_subarray_sum.rs b/src/problem/p209_minimum_size_subarray_sum.rs index c756c02..ed93504 100644 --- a/src/problem/p209_minimum_size_subarray_sum.rs +++ b/src/problem/p209_minimum_size_subarray_sum.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -41,6 +40,5 @@ mod tests { use super::*; #[test] - fn test_209() { - } + fn test_209() {} } diff --git a/src/problem/p20_valid_parentheses.rs b/src/problem/p20_valid_parentheses.rs index d1bef4a..cc85500 100644 --- a/src/problem/p20_valid_parentheses.rs +++ b/src/problem/p20_valid_parentheses.rs @@ -10,26 +10,26 @@ * * * Example 1: - * + * * Input: s = "()" * Output: true - * + * * Example 2: - * + * * Input: s = "()[]{}" * Output: true - * + * * Example 3: - * + * * Input: s = "(]" * Output: false - * + * * * Constraints: - * + * * 1 <= s.length <= 10^4 * s consists of parentheses only '()[]{}'. - * + * */ pub struct Solution {} @@ -48,23 +48,21 @@ impl Solution { for c in s.chars() { if left.contains(&c) { stack.push(c) - } - else if right.contains(&c) { + } else if right.contains(&c) { let target = match c { ')' => '(', ']' => '[', '}' => '{', - _ => return false + _ => return false, }; if stack.ends_with(&[target]) { stack.pop(); - } - else { - return false + } else { + return false; } } else { - return false + return false; } } diff --git a/src/problem/p210_course_schedule_ii.rs b/src/problem/p210_course_schedule_ii.rs index 4a19a38..680afb8 100644 --- a/src/problem/p210_course_schedule_ii.rs +++ b/src/problem/p210_course_schedule_ii.rs @@ -3,15 +3,14 @@ */ pub struct Solution {} - // submission codes start here use std::collections::VecDeque; impl Solution { pub fn find_order(num_courses: i32, prerequisites: Vec>) -> Vec { let num = num_courses as usize; - let mut edges = vec![vec![];num]; - let mut in_degs = vec![0;num]; + let mut edges = vec![vec![]; num]; + let mut in_degs = vec![0; num]; for edge in prerequisites { let (x, y) = (edge[1] as usize, edge[0] as usize); @@ -58,6 +57,5 @@ mod tests { use super::*; #[test] - fn test_210() { - } + fn test_210() {} } diff --git a/src/problem/p211_design_add_and_search_words_data_structure.rs b/src/problem/p211_design_add_and_search_words_data_structure.rs index 1a02d42..04ee221 100644 --- a/src/problem/p211_design_add_and_search_words_data_structure.rs +++ b/src/problem/p211_design_add_and_search_words_data_structure.rs @@ -4,7 +4,11 @@ pub struct Solution {} // submission codes start here -use std::{rc::Rc, cell::RefCell, collections::{HashMap, VecDeque}}; +use std::{ + cell::RefCell, + collections::{HashMap, VecDeque}, + rc::Rc, +}; struct TireNode { is_word: bool, @@ -31,7 +35,7 @@ struct WordDictionary { impl WordDictionary { fn new() -> Self { WordDictionary { - dummy_head: Rc::new(RefCell::new(TireNode::new(false))) + dummy_head: Rc::new(RefCell::new(TireNode::new(false))), } } @@ -41,16 +45,17 @@ impl WordDictionary { for (i, c) in word.chars().enumerate() { if node.borrow().next.contains_key(&c) { if i == word.len() - 1 { - node.borrow().next - .get(&c) - .unwrap() - .borrow_mut().is_word = true; + node.borrow().next.get(&c).unwrap().borrow_mut().is_word = true; } } else { if i == word.len() - 1 { - node.borrow_mut().next.insert(c, Rc::new(RefCell::new(TireNode::new(true)))); + node.borrow_mut() + .next + .insert(c, Rc::new(RefCell::new(TireNode::new(true)))); } else { - node.borrow_mut().next.insert(c, Rc::new(RefCell::new(TireNode::new(false)))); + node.borrow_mut() + .next + .insert(c, Rc::new(RefCell::new(TireNode::new(false)))); } } @@ -74,9 +79,7 @@ impl WordDictionary { let node = queue.pop_front().unwrap(); if i == word.len() - 1 { - if c == '.' && node.borrow().next.iter().any(|(_, n)| { - n.borrow().is_word - }) { + if c == '.' && node.borrow().next.iter().any(|(_, n)| n.borrow().is_word) { return true; } diff --git a/src/problem/p2129_capitalize_the_title.rs b/src/problem/p2129_capitalize_the_title.rs index 82fefd0..28a97f2 100644 --- a/src/problem/p2129_capitalize_the_title.rs +++ b/src/problem/p2129_capitalize_the_title.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -31,7 +30,13 @@ mod tests { #[test] fn test_2129() { - assert_eq!("Capitalize The Title", Solution::capitalize_title("capiTalIze tHe titLe".to_owned())); - assert_eq!("First Letter of Each Word", Solution::capitalize_title("First leTTeR of EACH Word".to_owned())); + assert_eq!( + "Capitalize The Title", + Solution::capitalize_title("capiTalIze tHe titLe".to_owned()) + ); + assert_eq!( + "First Letter of Each Word", + Solution::capitalize_title("First leTTeR of EACH Word".to_owned()) + ); } } diff --git a/src/problem/p212_word_search_ii.rs b/src/problem/p212_word_search_ii.rs index 2a46a85..ff36921 100644 --- a/src/problem/p212_word_search_ii.rs +++ b/src/problem/p212_word_search_ii.rs @@ -3,9 +3,12 @@ */ pub struct Solution {} - // submission codes start here -use std::{rc::Rc, cell::RefCell, collections::{HashMap, HashSet}}; +use std::{ + cell::RefCell, + collections::{HashMap, HashSet}, + rc::Rc, +}; #[derive(Debug)] struct TrieNode { @@ -39,9 +42,13 @@ impl Solution { } } else { if i == word.len() - 1 { - node.borrow_mut().next.insert(c, Rc::new(RefCell::new(TrieNode::new(true, index)))); + node.borrow_mut() + .next + .insert(c, Rc::new(RefCell::new(TrieNode::new(true, index)))); } else { - node.borrow_mut().next.insert(c, Rc::new(RefCell::new(TrieNode::new(false, usize::MAX)))); + node.borrow_mut() + .next + .insert(c, Rc::new(RefCell::new(TrieNode::new(false, usize::MAX)))); } }; @@ -63,8 +70,15 @@ impl Solution { result.iter().map(|s| s.to_owned()).collect() } - fn dfs(board: &Vec>, node: &Rc>, words: &Vec, result: &mut HashSet, - visited: &mut Vec>, x: i32, y: i32) { + fn dfs( + board: &Vec>, + node: &Rc>, + words: &Vec, + result: &mut HashSet, + visited: &mut Vec>, + x: i32, + y: i32, + ) { let (m, n) = (board.len() as i32, board[0].len() as i32); if x < 0 || x >= m || y < 0 || y >= n { @@ -88,7 +102,7 @@ impl Solution { Self::dfs(board, next, words, result, visited, x + 1, y); Self::dfs(board, next, words, result, visited, x, y - 1); }; - + visited[x as usize][y as usize] = false; } } @@ -105,7 +119,7 @@ mod tests { vec!['o', 'a', 'a', 'n'], vec!['e', 't', 'a', 'e'], vec!['i', 'h', 'k', 'r'], - vec!['i', 'f', 'l', 'v'] + vec!['i', 'f', 'l', 'v'], ]; let words = vec_string!("oath", "pea", "eat", "rain"); @@ -120,9 +134,7 @@ mod tests { #[test] fn test_212_2() { - let board = vec![ - vec!['a', 'a'] - ]; + let board = vec![vec!['a', 'a']]; let words = vec_string!("aaa"); @@ -130,19 +142,19 @@ mod tests { assert_eq!(result.len(), 0); } - + #[test] fn test_212_3() { let board = vec![ vec!['a', 'b', 'c', 'e'], vec!['x', 'x', 'c', 'd'], - vec!['x', 'x', 'b', 'a'] + vec!['x', 'x', 'b', 'a'], ]; - + let words = vec_string!("abc", "abcd"); - + let result = Solution::find_words(board, words); - + assert_eq!(result.len(), 2); assert!(result.contains(&"abc".to_owned())); assert!(result.contains(&"abcd".to_owned())); diff --git a/src/problem/p215_kth_largest_element_in_an_array.rs b/src/problem/p215_kth_largest_element_in_an_array.rs index 304d3f0..ee09842 100644 --- a/src/problem/p215_kth_largest_element_in_an_array.rs +++ b/src/problem/p215_kth_largest_element_in_an_array.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p2171_removing_minimum_number_of_magic_beans.rs b/src/problem/p2171_removing_minimum_number_of_magic_beans.rs index c4f7b13..dd74d19 100644 --- a/src/problem/p2171_removing_minimum_number_of_magic_beans.rs +++ b/src/problem/p2171_removing_minimum_number_of_magic_beans.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::cmp::min; @@ -19,8 +18,7 @@ impl Solution { let mut result = i64::MAX; for (index, value) in (&beans).iter().enumerate() { - result = min(result, - sum - (*value as i64) * (beans.len() - index) as i64); + result = min(result, sum - (*value as i64) * (beans.len() - index) as i64); } result @@ -35,7 +33,7 @@ mod tests { #[test] fn test_2171() { - assert_eq!(Solution::minimum_removal(vec![4,1,6,5]), 4); - assert_eq!(Solution::minimum_removal(vec![2,10,3,2]), 7); + assert_eq!(Solution::minimum_removal(vec![4, 1, 6, 5]), 4); + assert_eq!(Solution::minimum_removal(vec![2, 10, 3, 2]), 7); } } diff --git a/src/problem/p2181_merge_nodes_in_between_zeros.rs b/src/problem/p2181_merge_nodes_in_between_zeros.rs index 0b5f467..b9d8be9 100644 --- a/src/problem/p2181_merge_nodes_in_between_zeros.rs +++ b/src/problem/p2181_merge_nodes_in_between_zeros.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::linked_list::{ListNode, to_list}; +use crate::util::linked_list::{to_list, ListNode}; // submission codes start here @@ -62,7 +62,13 @@ mod tests { #[test] fn test_2181() { - assert_eq!(to_list(vec![4, 11]), Solution::merge_nodes(to_list(vec![0, 3, 1, 0, 4, 5, 2, 0]))); - assert_eq!(to_list(vec![1, 3, 4]), Solution::merge_nodes(to_list(vec![0, 1, 0, 3, 0, 2, 2, 0]))); + assert_eq!( + to_list(vec![4, 11]), + Solution::merge_nodes(to_list(vec![0, 3, 1, 0, 4, 5, 2, 0])) + ); + assert_eq!( + to_list(vec![1, 3, 4]), + Solution::merge_nodes(to_list(vec![0, 1, 0, 3, 0, 2, 2, 0])) + ); } } diff --git a/src/problem/p2182_construct_string_with_repeat_limit.rs b/src/problem/p2182_construct_string_with_repeat_limit.rs index 05a9b30..dddfef9 100644 --- a/src/problem/p2182_construct_string_with_repeat_limit.rs +++ b/src/problem/p2182_construct_string_with_repeat_limit.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::BTreeMap; @@ -59,11 +58,13 @@ mod tests { #[test] fn test_2182() { - assert_eq!(String::from("zzcccac"), Solution::repeat_limited_string( - String::from("cczazcc"), 3 - )); - assert_eq!(String::from("bbabaa"), Solution::repeat_limited_string( - String::from("aababab"), 2 - )); + assert_eq!( + String::from("zzcccac"), + Solution::repeat_limited_string(String::from("cczazcc"), 3) + ); + assert_eq!( + String::from("bbabaa"), + Solution::repeat_limited_string(String::from("aababab"), 2) + ); } } diff --git a/src/problem/p2187_minimum_time_to_complete_trips.rs b/src/problem/p2187_minimum_time_to_complete_trips.rs index 4c27825..0b92c75 100644 --- a/src/problem/p2187_minimum_time_to_complete_trips.rs +++ b/src/problem/p2187_minimum_time_to_complete_trips.rs @@ -3,37 +3,36 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn minimum_time(time: Vec, total_trips: i32) -> i64 { let time: Vec = time.iter().map(|x| *x as i64).collect(); let total_trips = total_trips as i64; - + let check = |t: i64| -> bool { let mut trips = 0; - + for &bus in time.iter() { trips += t / bus; } - + trips >= total_trips }; - + let mut left = 0; let mut right = time[0] * total_trips; - + while left < right { let middle = (right - left) / 2 + left; - + if check(middle) { right = middle; - } else { + } else { left = middle + 1; } } - + right } } @@ -46,7 +45,7 @@ mod tests { #[test] fn test_2187() { - assert_eq!(3, Solution::minimum_time(vec![1,2,3], 5)); + assert_eq!(3, Solution::minimum_time(vec![1, 2, 3], 5)); assert_eq!(2, Solution::minimum_time(vec![2], 1)); } } diff --git a/src/problem/p219_contains_duplicate_ii.rs b/src/problem/p219_contains_duplicate_ii.rs index ba5d31d..76e468a 100644 --- a/src/problem/p219_contains_duplicate_ii.rs +++ b/src/problem/p219_contains_duplicate_ii.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -13,7 +12,7 @@ impl Solution { for (i, v) in nums.iter().enumerate() { if let Some(last_pos) = map.get_mut(v) { - let distance:i32 = (*last_pos - i as i32); + let distance: i32 = (*last_pos - i as i32); let distance = distance.abs(); if distance > 0 && distance <= k { @@ -21,9 +20,8 @@ impl Solution { } else { *last_pos = i as i32; } - } else { - map.insert(*v, i as i32); + map.insert(*v, i as i32); } } @@ -39,7 +37,10 @@ mod tests { #[test] fn test_219() { - assert!(Solution::contains_nearby_duplicate(vec![1,2,3,1], 3)); - assert!(!Solution::contains_nearby_duplicate(vec![1,2,3,1,2,3], 2)); + assert!(Solution::contains_nearby_duplicate(vec![1, 2, 3, 1], 3)); + assert!(!Solution::contains_nearby_duplicate( + vec![1, 2, 3, 1, 2, 3], + 2 + )); } } diff --git a/src/problem/p21_merge_two_sorted_lists.rs b/src/problem/p21_merge_two_sorted_lists.rs index 9709446..01dcc86 100644 --- a/src/problem/p21_merge_two_sorted_lists.rs +++ b/src/problem/p21_merge_two_sorted_lists.rs @@ -5,7 +5,7 @@ pub struct Solution {} use std::borrow::{Borrow, BorrowMut}; -use crate::util::linked_list::{ListNode, to_list}; +use crate::util::linked_list::{to_list, ListNode}; // submission codes start here @@ -26,7 +26,10 @@ use crate::util::linked_list::{ListNode, to_list}; // } // } impl Solution { - pub fn merge_two_lists(list1: Option>, list2: Option>) -> Option> { + pub fn merge_two_lists( + list1: Option>, + list2: Option>, + ) -> Option> { let mut head = None; let mut now = &mut head; @@ -46,8 +49,8 @@ impl Solution { now = &mut now.insert(b).next } - }, - (x, y) => break x.or(y) + } + (x, y) => break x.or(y), } }; @@ -62,6 +65,5 @@ mod tests { use super::*; #[test] - fn test_21() { - } + fn test_21() {} } diff --git a/src/problem/p2207_maximize_number_of_subsequences_in_a_string.rs b/src/problem/p2207_maximize_number_of_subsequences_in_a_string.rs index 6fe274f..6c22e8c 100644 --- a/src/problem/p2207_maximize_number_of_subsequences_in_a_string.rs +++ b/src/problem/p2207_maximize_number_of_subsequences_in_a_string.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -19,7 +18,7 @@ impl Solution { result += first_count; second_count += 1; } - + if c == first { first_count += 1; } @@ -37,7 +36,13 @@ mod tests { #[test] fn test_2207() { - assert_eq!(4, Solution::maximum_subsequence_count("abdcdbc".to_owned(), "ac".to_owned())); - assert_eq!(6, Solution::maximum_subsequence_count("aabb".to_owned(), "ab".to_owned())); + assert_eq!( + 4, + Solution::maximum_subsequence_count("abdcdbc".to_owned(), "ac".to_owned()) + ); + assert_eq!( + 6, + Solution::maximum_subsequence_count("aabb".to_owned(), "ab".to_owned()) + ); } } diff --git a/src/problem/p221_maximal_square.rs b/src/problem/p221_maximal_square.rs index 111f6d0..b48a791 100644 --- a/src/problem/p221_maximal_square.rs +++ b/src/problem/p221_maximal_square.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -20,10 +19,10 @@ impl Solution { if i == 0 || j == 0 { dp[i][j] = 1; - } else { + } else { dp[i][j] = dp[i - 1][j - 1].min(dp[i - 1][j]).min(dp[i][j - 1]) + 1; } - + result = result.max(dp[i][j]); } } @@ -40,7 +39,10 @@ mod tests { #[test] fn test_221() { - assert_eq!(1, Solution::maximal_square(vec![vec!['0', '1'], vec!['1', '0']])); + assert_eq!( + 1, + Solution::maximal_square(vec![vec!['0', '1'], vec!['1', '0']]) + ); assert_eq!(0, Solution::maximal_square(vec![vec!['0']])); } } diff --git a/src/problem/p222_count_complete_tree_nodes.rs b/src/problem/p222_count_complete_tree_nodes.rs index 1edd9e2..dff691c 100644 --- a/src/problem/p222_count_complete_tree_nodes.rs +++ b/src/problem/p222_count_complete_tree_nodes.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,9 +25,9 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; use std::collections::VecDeque; +use std::rc::Rc; impl Solution { pub fn count_nodes(root: Option>>) -> i32 { let mut result = 0; @@ -43,7 +43,7 @@ impl Solution { let node = queue.pop_front().unwrap(); if let Some(left) = &node.borrow().left { - queue.push_back(Rc::clone(left)); + queue.push_back(Rc::clone(left)); }; if let Some(right) = &node.borrow().right { @@ -62,6 +62,5 @@ mod tests { use super::*; #[test] - fn test_222() { - } + fn test_222() {} } diff --git a/src/problem/p224_basic_calculator.rs b/src/problem/p224_basic_calculator.rs index 585c55b..a3a5be6 100644 --- a/src/problem/p224_basic_calculator.rs +++ b/src/problem/p224_basic_calculator.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -12,7 +11,7 @@ impl Solution { let mut result: i64 = 0; let mut sign = 1; - let s : Vec = s.chars().collect(); + let s: Vec = s.chars().collect(); let mut i = 0; diff --git a/src/problem/p225_implement_stack_using_queues.rs b/src/problem/p225_implement_stack_using_queues.rs index a36b049..8d2967a 100644 --- a/src/problem/p225_implement_stack_using_queues.rs +++ b/src/problem/p225_implement_stack_using_queues.rs @@ -3,27 +3,24 @@ */ pub struct Solution {} - // submission codes start here use std::collections::VecDeque; struct MyStack { - queue: VecDeque + queue: VecDeque, } - /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl MyStack { - fn new() -> Self { return MyStack { - queue: VecDeque::new() - } + queue: VecDeque::new(), + }; } - + fn push(&mut self, x: i32) { let mut new_queue = VecDeque::with_capacity(self.queue.capacity() + 1); new_queue.push_back(x); @@ -34,15 +31,15 @@ impl MyStack { self.queue = new_queue; } - + fn pop(&mut self) -> i32 { self.queue.pop_front().unwrap() } - + fn top(&self) -> i32 { *self.queue.front().unwrap() } - + fn empty(&self) -> bool { self.queue.is_empty() } diff --git a/src/problem/p226_invert_binary_tree.rs b/src/problem/p226_invert_binary_tree.rs index fab6b4f..db3ccda 100644 --- a/src/problem/p226_invert_binary_tree.rs +++ b/src/problem/p226_invert_binary_tree.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,26 +25,22 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn invert_tree(root: Option>>) -> Option>> { match root { None => None, Some(root) => { - let left = Self::invert_tree( - root.borrow_mut().left.take() - ); - let right = Self::invert_tree( - root.borrow_mut().right.take() - ); + let left = Self::invert_tree(root.borrow_mut().left.take()); + let right = Self::invert_tree(root.borrow_mut().right.take()); root.borrow_mut().left = right; root.borrow_mut().right = left; Some(root) } - } + } } } diff --git a/src/problem/p2286_booking_concert_tickets_in_groups.rs b/src/problem/p2286_booking_concert_tickets_in_groups.rs index 3a3a9ca..25df7a4 100644 --- a/src/problem/p2286_booking_concert_tickets_in_groups.rs +++ b/src/problem/p2286_booking_concert_tickets_in_groups.rs @@ -3,14 +3,13 @@ */ pub struct Solution {} - // submission codes start here struct BookMyShow { row_count: i32, column_count: i32, min_tree: Vec, - sum_tree: Vec + sum_tree: Vec, } /** @@ -24,81 +23,81 @@ impl BookMyShow { row_count: n, column_count: m, min_tree: vec![0; segement_depth], - sum_tree: vec![0; segement_depth] + sum_tree: vec![0; segement_depth], } } - + fn modify(&mut self, i: usize, l: i32, r: i32, index: i32, val: i32) { if l == r { self.min_tree[i] = val; self.sum_tree[i] = val as i64; return; } - + let middle = (l + r) / 2; if index <= middle { self.modify(i * 2, l, middle, index, val); - } else { + } else { self.modify(i * 2 + 1, middle + 1, r, index, val) } - + self.min_tree[i] = self.min_tree[i * 2].min(self.min_tree[i * 2 + 1]); self.sum_tree[i] = self.sum_tree[i * 2] + self.sum_tree[i * 2 + 1]; } - + fn query_min_row(&self, i: usize, l: i32, r: i32, val: i32) -> i32 { if l == r { return if self.min_tree[i] > val { self.row_count - } else { - l - } + } else { + l + }; } - + let middle = (l + r) / 2; if self.min_tree[i * 2] <= val { self.query_min_row(i * 2, l, middle, val) - } else { + } else { self.query_min_row(i * 2 + 1, middle + 1, r, val) } } - + fn query_sum(&self, i: usize, l: i32, r: i32, target_left: i32, target_right: i32) -> i64 { if target_left <= l && r <= target_right { return self.sum_tree[i]; } - + let middle = (l + r) / 2; let mut result = 0; - + if middle >= target_left { result += self.query_sum(i * 2, l, middle, target_left, target_right) } - + if middle + 1 <= target_right { result += self.query_sum(i * 2 + 1, middle + 1, r, target_left, target_right); } - + result } - + fn gather(&mut self, k: i32, max_row: i32) -> Vec { let target_row = self.query_min_row(1, 0, self.row_count - 1, self.column_count - k); if target_row > max_row { return vec![]; } - + let used = self.query_sum(1, 0, self.row_count - 1, target_row, target_row) as i32; self.modify(1, 0, self.row_count - 1, target_row, used + k); vec![target_row, used] } - + fn scatter(&mut self, k: i32, max_row: i32) -> bool { let used = self.query_sum(1, 0, self.row_count - 1, 0, max_row); if ((max_row + 1) as i64 * self.column_count as i64) - used < k as i64 { return false; } - + let mut target_row = self.query_min_row(1, 0, self.row_count - 1, self.column_count - 1); let mut k = k; loop { @@ -107,12 +106,12 @@ impl BookMyShow { self.modify(1, 0, self.row_count - 1, target_row, used + k); break; } - + k -= self.column_count - used; self.modify(1, 0, self.row_count - 1, target_row, self.column_count); target_row += 1; } - + true } } @@ -133,17 +132,17 @@ mod tests { #[test] fn test_2286_1() { let mut show = BookMyShow::new(2, 5); - - assert_eq!(vec![0,0], show.gather(4, 0)); + + assert_eq!(vec![0, 0], show.gather(4, 0)); assert_eq!(Vec::::new(), show.gather(2, 0)); assert!(show.scatter(5, 1)); assert!(!show.scatter(5, 1)); } - + #[test] fn test_2286_2() { let mut show = BookMyShow::new(5, 9); - + assert_eq!(Vec::::new(), show.gather(10, 1)); assert!(show.scatter(3, 3)); assert_eq!(vec![1, 0], show.gather(9, 1)); diff --git a/src/problem/p228_summary_ranges.rs b/src/problem/p228_summary_ranges.rs index b931932..0f555f8 100644 --- a/src/problem/p228_summary_ranges.rs +++ b/src/problem/p228_summary_ranges.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -49,6 +48,5 @@ mod tests { use super::*; #[test] - fn test_228() { - } + fn test_228() {} } diff --git a/src/problem/p22_generate_parentheses.rs b/src/problem/p22_generate_parentheses.rs index efee0f5..e4d4ae2 100644 --- a/src/problem/p22_generate_parentheses.rs +++ b/src/problem/p22_generate_parentheses.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -11,31 +10,31 @@ impl Solution { let n = n as usize; let mut result = vec![]; let mut path = Vec::with_capacity(n * 2); - + Self::backtrace(n, 0, &mut path, &mut result); - + result } - + fn backtrace(left: usize, right: usize, path: &mut Vec, result: &mut Vec) { if left == 0 && right == 0 { let t = path.clone(); result.push(t.iter().collect()); return; } - + if left != 0 { path.push('('); Self::backtrace(left - 1, right + 1, path, result); path.pop(); } - + if right != 0 { path.push(')'); Self::backtrace(left, right - 1, path, result); path.pop(); } - } + } } // submission codes end @@ -45,6 +44,5 @@ mod tests { use super::*; #[test] - fn test_22() { - } + fn test_22() {} } diff --git a/src/problem/p2306_naming_a_company.rs b/src/problem/p2306_naming_a_company.rs index 66a72b7..a60e720 100644 --- a/src/problem/p2306_naming_a_company.rs +++ b/src/problem/p2306_naming_a_company.rs @@ -3,31 +3,31 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn distinct_names(ideas: Vec) -> i64 { - use std::collections::{HashSet, HashMap}; - + use std::collections::{HashMap, HashSet}; + let mut map = HashMap::new(); - + for idea in ideas.iter() { let entry = map.entry(&idea[..1]).or_insert(HashSet::new()); entry.insert(&idea[1..]); } - + let mut result = 0; let values: Vec> = map.into_iter().map(|p| p.1).collect(); - + for i in 0..values.len() { for j in i + 1..values.len() { let intersect = values[i].intersection(&values[j]).count(); - - result += (values[i].len() - intersect) as i64 * (values[j].len() - intersect) as i64 + + result += + (values[i].len() - intersect) as i64 * (values[j].len() - intersect) as i64 } } - + result * 2 } } @@ -40,7 +40,10 @@ mod tests { #[test] fn test_2306() { - assert_eq!(6, Solution::distinct_names(vec_string!("coffee", "donuts", "time", "toffee"))); + assert_eq!( + 6, + Solution::distinct_names(vec_string!("coffee", "donuts", "time", "toffee")) + ); assert_eq!(0, Solution::distinct_names(vec_string!("lack", "back"))); } } diff --git a/src/problem/p230_kth_smallest_element_in_a_bst.rs b/src/problem/p230_kth_smallest_element_in_a_bst.rs index fb521e8..d7d0ce9 100644 --- a/src/problem/p230_kth_smallest_element_in_a_bst.rs +++ b/src/problem/p230_kth_smallest_element_in_a_bst.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,8 +25,8 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { fn inorder_iterate(node: &Rc>, count: &mut i32, target: i32) -> Option { if let Some(left) = node.borrow().left.as_ref() { @@ -41,7 +41,7 @@ impl Solution { } if let Some(right) = node.borrow().right.as_ref() { - if let Some(result) = Self::inorder_iterate(right, count, target) { + if let Some(result) = Self::inorder_iterate(right, count, target) { return Some(result); } } @@ -53,7 +53,7 @@ impl Solution { let mut count = 0; if let Some(root) = root { - return Self::inorder_iterate(&root, &mut count, k).unwrap() + return Self::inorder_iterate(&root, &mut count, k).unwrap(); } 0 @@ -67,6 +67,5 @@ mod tests { use super::*; #[test] - fn test_230() { - } + fn test_230() {} } diff --git a/src/problem/p2312_selling_pieces_of_wood.rs b/src/problem/p2312_selling_pieces_of_wood.rs index 8c9c2ce..acf5256 100644 --- a/src/problem/p2312_selling_pieces_of_wood.rs +++ b/src/problem/p2312_selling_pieces_of_wood.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -12,19 +11,20 @@ impl Solution { let mut prices_map = HashMap::with_capacity(prices.len()); for price in prices { - prices_map.insert(Solution::hash(price[0] as usize, price[1] as usize), - price[2] as i64); + prices_map.insert( + Solution::hash(price[0] as usize, price[1] as usize), + price[2] as i64, + ); } - + let (m, n) = (m as usize, n as usize); - let mut dp = vec![vec![-1;n + 1];m + 1]; - + let mut dp = vec![vec![-1; n + 1]; m + 1]; Solution::dfs(m, n, &mut dp, &prices_map) } - fn hash(x: usize, y: usize)-> usize { + fn hash(x: usize, y: usize) -> usize { return x * 1000 + y; } @@ -33,20 +33,21 @@ impl Solution { return dp[x][y]; } - let mut result = *prices_map.get(&Solution::hash(x, y)) - .unwrap_or_else(|| &0); + let mut result = *prices_map.get(&Solution::hash(x, y)).unwrap_or_else(|| &0); if x > 1 { - for i in 1..x { - result = result.max(Solution::dfs(i, y, dp, prices_map) + - Solution::dfs(x - i, y, dp, prices_map)); + for i in 1..x { + result = result.max( + Solution::dfs(i, y, dp, prices_map) + Solution::dfs(x - i, y, dp, prices_map), + ); } } if y > 1 { for j in 1..y { - result = result.max(Solution::dfs(x, j, dp, prices_map) + - Solution::dfs(x, y - j, dp, prices_map)); + result = result.max( + Solution::dfs(x, j, dp, prices_map) + Solution::dfs(x, y - j, dp, prices_map), + ); } } @@ -62,6 +63,5 @@ mod tests { use super::*; #[test] - fn test_2312() { - } + fn test_2312() {} } diff --git a/src/problem/p232_implement_queue_using_stacks.rs b/src/problem/p232_implement_queue_using_stacks.rs index 85f1136..6d7a33f 100644 --- a/src/problem/p232_implement_queue_using_stacks.rs +++ b/src/problem/p232_implement_queue_using_stacks.rs @@ -3,33 +3,30 @@ */ pub struct Solution {} - // submission codes start here use std::collections::VecDeque; struct MyQueue { in_stack: VecDeque, - out_stack: VecDeque + out_stack: VecDeque, } - /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl MyQueue { - fn new() -> Self { MyQueue { in_stack: VecDeque::new(), - out_stack: VecDeque::new() + out_stack: VecDeque::new(), } } - + fn push(&mut self, x: i32) { self.in_stack.push_back(x); } - + fn pop(&mut self) -> i32 { if self.out_stack.is_empty() { while let Some(top) = self.in_stack.pop_back() { @@ -39,7 +36,7 @@ impl MyQueue { self.out_stack.pop_back().unwrap() } - + fn peek(&mut self) -> i32 { if self.out_stack.is_empty() { while let Some(top) = self.in_stack.pop_back() { @@ -49,7 +46,7 @@ impl MyQueue { *self.out_stack.back().unwrap() } - + fn empty(&self) -> bool { self.out_stack.is_empty() && self.in_stack.is_empty() } diff --git a/src/problem/p2332_the_latest_time_to_catch_a_bus.rs b/src/problem/p2332_the_latest_time_to_catch_a_bus.rs index 70e694d..8bbc845 100644 --- a/src/problem/p2332_the_latest_time_to_catch_a_bus.rs +++ b/src/problem/p2332_the_latest_time_to_catch_a_bus.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -27,7 +26,7 @@ impl Solution { break; } } - + // 无论坐没坐满都要发车 last_passengers = now_passengers; now_passengers = 0; @@ -36,11 +35,11 @@ impl Solution { // 最后一个上车的哥们 let mut down_passenger = if last_passenger == 0 { // 特判一下如果没有哥们可以上车的情况 - return buses[n - 1] - } else { + return buses[n - 1]; + } else { last_passenger - 1 }; - + let mut result = if last_passengers < capacity { // 最后一辆车上还有空位 // 直接在最后一辆车来之前上车 @@ -57,11 +56,10 @@ impl Solution { } down_passenger -= 1; - + result }; - loop { if result != passengers[down_passenger] { break; @@ -73,7 +71,7 @@ impl Solution { } down_passenger -= 1; } - + result } } @@ -86,9 +84,22 @@ mod tests { #[test] fn test_2332() { - assert_eq!(16, Solution::latest_time_catch_the_bus(vec![10, 20], vec![2, 17, 18, 19], 2)); - assert_eq!(20, Solution::latest_time_catch_the_bus(vec![20, 30, 10], vec![19, 13, 26, 4, 25, 11, 21], 2)); - assert_eq!(1, Solution::latest_time_catch_the_bus(vec![3], vec![2,3], 2)); + assert_eq!( + 16, + Solution::latest_time_catch_the_bus(vec![10, 20], vec![2, 17, 18, 19], 2) + ); + assert_eq!( + 20, + Solution::latest_time_catch_the_bus( + vec![20, 30, 10], + vec![19, 13, 26, 4, 25, 11, 21], + 2 + ) + ); + assert_eq!( + 1, + Solution::latest_time_catch_the_bus(vec![3], vec![2, 3], 2) + ); assert_eq!(1, Solution::latest_time_catch_the_bus(vec![2], vec![2], 1)); assert_eq!(1, Solution::latest_time_catch_the_bus(vec![2], vec![2], 2)); assert_eq!(3, Solution::latest_time_catch_the_bus(vec![3], vec![4], 1)); diff --git a/src/problem/p235_lowest_common_ancestor_of_a_binary_search_tree.rs b/src/problem/p235_lowest_common_ancestor_of_a_binary_search_tree.rs index fe3d894..665d32b 100644 --- a/src/problem/p235_lowest_common_ancestor_of_a_binary_search_tree.rs +++ b/src/problem/p235_lowest_common_ancestor_of_a_binary_search_tree.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -14,7 +14,7 @@ use crate::util::tree::{TreeNode, to_tree}; // pub left: Option>>, // pub right: Option>>, // } -// +// // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { @@ -25,22 +25,30 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { - pub fn lowest_common_ancestor(root: Option>>, p: Option>>, q: Option>>) -> Option>> { + pub fn lowest_common_ancestor( + root: Option>>, + p: Option>>, + q: Option>>, + ) -> Option>> { let (root, p, q) = (root?, p?, q?); let mut ancestor = root; loop { - ancestor = if p.borrow().val < ancestor.borrow().val && q.borrow().val < ancestor.borrow().val { + ancestor = if p.borrow().val < ancestor.borrow().val + && q.borrow().val < ancestor.borrow().val + { Rc::clone(&ancestor.borrow().left.as_ref().unwrap()) - } else if (p.borrow().val > ancestor.borrow().val && q.borrow().val > ancestor.borrow().val ) { + } else if (p.borrow().val > ancestor.borrow().val + && q.borrow().val > ancestor.borrow().val) + { Rc::clone(&ancestor.borrow().right.as_ref().unwrap()) } else { break; } - } + } Some(ancestor) } @@ -53,6 +61,5 @@ mod tests { use super::*; #[test] - fn test_235() { - } + fn test_235() {} } diff --git a/src/problem/p2368_reachable_nodes_with_restrictions.rs b/src/problem/p2368_reachable_nodes_with_restrictions.rs index ab94918..f7a4b62 100644 --- a/src/problem/p2368_reachable_nodes_with_restrictions.rs +++ b/src/problem/p2368_reachable_nodes_with_restrictions.rs @@ -3,16 +3,15 @@ */ pub struct Solution {} - // submission codes start here -use std::collections::VecDeque; use std::collections::HashSet; +use std::collections::VecDeque; impl Solution { pub fn reachable_nodes(n: i32, edges: Vec>, restricted: Vec) -> i32 { let mut result = 0; let n = n as usize; - let mut graph = vec![vec![];n + 1]; + let mut graph = vec![vec![]; n + 1]; for edge in edges { let x = edge[0] as usize; @@ -25,7 +24,7 @@ impl Solution { let mut queue = VecDeque::new(); let mut visited = HashSet::new(); let mut unreachable = HashSet::with_capacity(restricted.len()); - + for node in restricted { unreachable.insert(node as usize); } @@ -58,6 +57,5 @@ mod tests { use super::*; #[test] - fn test_2368() { - } + fn test_2368() {} } diff --git a/src/problem/p236_lowest_common_ancestor_of_a_binary_tree.rs b/src/problem/p236_lowest_common_ancestor_of_a_binary_tree.rs index a161d5d..310da29 100644 --- a/src/problem/p236_lowest_common_ancestor_of_a_binary_tree.rs +++ b/src/problem/p236_lowest_common_ancestor_of_a_binary_tree.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -14,7 +14,7 @@ use crate::util::tree::{TreeNode, to_tree}; // pub left: Option>>, // pub right: Option>>, // } -// +// // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { @@ -25,10 +25,14 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { - pub fn lowest_common_ancestor(root: Option>>, p: Option>>, q: Option>>) -> Option>> { + pub fn lowest_common_ancestor( + root: Option>>, + p: Option>>, + q: Option>>, + ) -> Option>> { if root.is_none() || root == p || root == q { return root; } @@ -36,13 +40,13 @@ impl Solution { let left = Solution::lowest_common_ancestor( root.as_ref().unwrap().borrow_mut().left.take(), p.clone(), - q.clone() + q.clone(), ); let right = Solution::lowest_common_ancestor( root.as_ref().unwrap().borrow_mut().right.take(), p.clone(), - q.clone() + q.clone(), ); if left.is_some() && right.is_some() { @@ -64,6 +68,5 @@ mod tests { use super::*; #[test] - fn test_236() { - } + fn test_236() {} } diff --git a/src/problem/p2374_node_with_highest_edge_score.rs b/src/problem/p2374_node_with_highest_edge_score.rs index f884b00..a7d5735 100644 --- a/src/problem/p2374_node_with_highest_edge_score.rs +++ b/src/problem/p2374_node_with_highest_edge_score.rs @@ -1,16 +1,14 @@ - /** * [2374] Node With Highest Edge Score */ pub struct Solution {} - // submission codes start here impl Solution { pub fn edge_score(edges: Vec) -> i32 { - use std::collections::HashMap; use std::cmp::Ordering; + use std::collections::HashMap; let mut map = HashMap::new(); @@ -18,14 +16,15 @@ impl Solution { let entry = map.entry(v).or_insert(0); *entry += i; } - - *map.iter().max_by(|a, b| { - match a.1.cmp(b.1) { - Ordering::Less => { Ordering::Less } - Ordering::Equal => { b.0.cmp(a.0) } - Ordering::Greater => { Ordering::Greater } - } - }).unwrap().0 + + *map.iter() + .max_by(|a, b| match a.1.cmp(b.1) { + Ordering::Less => Ordering::Less, + Ordering::Equal => b.0.cmp(a.0), + Ordering::Greater => Ordering::Greater, + }) + .unwrap() + .0 } } diff --git a/src/problem/p2376_count_special_integers.rs b/src/problem/p2376_count_special_integers.rs index ac37f09..1171dc6 100644 --- a/src/problem/p2376_count_special_integers.rs +++ b/src/problem/p2376_count_special_integers.rs @@ -1,17 +1,18 @@ - /** * [2376] Count Special Integers */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; impl Solution { pub fn count_special_numbers(n: i32) -> i32 { - - let n: Vec = n.to_string().chars().map(|c| c.to_digit(10).unwrap() as i32).collect(); + let n: Vec = n + .to_string() + .chars() + .map(|c| c.to_digit(10).unwrap() as i32) + .collect(); let mut result = 0; let mut candidate = 9; @@ -23,44 +24,42 @@ impl Solution { } let mut memory: HashMap = HashMap::new(); - + result += Self::dp(0, false, &mut memory, &n); result } - + // mask 表示前缀中使用过的数字 使用二进制表示 // prefix_smaller 当前的前缀是否小于n的前缀 - fn dp(mask: i32, prefix_smaller: bool, memory: &mut HashMap, number: &Vec) -> i32 { + fn dp( + mask: i32, + prefix_smaller: bool, + memory: &mut HashMap, + number: &Vec, + ) -> i32 { let used_bits = mask.count_ones() as usize; if used_bits == number.len() { return 1; } - let key = mask * 2 + if prefix_smaller { - 1 - } else { - 0 - }; - + let key = mask * 2 + if prefix_smaller { 1 } else { 0 }; + if !memory.contains_key(&key) { let mut result = 0; - let lower_bound = if mask == 0 { - 1 - } else { - 0 - }; + let lower_bound = if mask == 0 { 1 } else { 0 }; - let upper_bound = if prefix_smaller { - 9 - } else { - number[used_bits] - }; + let upper_bound = if prefix_smaller { 9 } else { number[used_bits] }; for i in lower_bound..=upper_bound { if mask >> i & 1 == 0 { - result += Self::dp(mask | 1 << i, prefix_smaller || i < upper_bound, memory, number); + result += Self::dp( + mask | 1 << i, + prefix_smaller || i < upper_bound, + memory, + number, + ); } } diff --git a/src/problem/p2390_removing_stars_from_a_string.rs b/src/problem/p2390_removing_stars_from_a_string.rs index 1a87335..07ba0c9 100644 --- a/src/problem/p2390_removing_stars_from_a_string.rs +++ b/src/problem/p2390_removing_stars_from_a_string.rs @@ -3,26 +3,25 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn remove_stars(s: String) -> String { - let s : Vec = s.chars().collect(); - + let s: Vec = s.chars().collect(); + let mut result = Vec::with_capacity(s.len()); - + for i in s { - match i { + match i { '*' => { - result.pop(); + result.pop(); } _ => { result.push(i); } } } - + result.iter().collect() } } @@ -35,7 +34,13 @@ mod tests { #[test] fn test_2390() { - assert_eq!("lecoe".to_owned(), Solution::remove_stars("leet**cod*e".to_owned())); - assert_eq!("".to_owned(), Solution::remove_stars("erase*****".to_owned())); + assert_eq!( + "lecoe".to_owned(), + Solution::remove_stars("leet**cod*e".to_owned()) + ); + assert_eq!( + "".to_owned(), + Solution::remove_stars("erase*****".to_owned()) + ); } } diff --git a/src/problem/p2398_maximum_number_of_robots_within_budget.rs b/src/problem/p2398_maximum_number_of_robots_within_budget.rs index c08867e..16f6fc8 100644 --- a/src/problem/p2398_maximum_number_of_robots_within_budget.rs +++ b/src/problem/p2398_maximum_number_of_robots_within_budget.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -33,7 +32,11 @@ impl Solution { queue.push_back(i); // 判断当前left开始的机器人是否会导致超过预算 - while left <= i && (i - left + 1) as i64 * running_costs_sum + charge_times[*queue.front().unwrap()] as i64 > budget { + while left <= i + && (i - left + 1) as i64 * running_costs_sum + + charge_times[*queue.front().unwrap()] as i64 + > budget + { if let Some(&front) = queue.front() { if front == left { queue.pop_front(); @@ -60,7 +63,13 @@ mod tests { #[test] fn test_2398() { - assert_eq!(3, Solution::maximum_robots(vec![3, 6, 1, 3, 4], vec![2, 1, 3, 4, 5], 25)); - assert_eq!(0, Solution::maximum_robots(vec![11, 12, 19], vec![10, 8, 7], 19)); + assert_eq!( + 3, + Solution::maximum_robots(vec![3, 6, 1, 3, 4], vec![2, 1, 3, 4, 5], 25) + ); + assert_eq!( + 0, + Solution::maximum_robots(vec![11, 12, 19], vec![10, 8, 7], 19) + ); } } diff --git a/src/problem/p2414_length_of_the_longest_alphabetical_continuous_substring.rs b/src/problem/p2414_length_of_the_longest_alphabetical_continuous_substring.rs index 627a8ab..7d16ef0 100644 --- a/src/problem/p2414_length_of_the_longest_alphabetical_continuous_substring.rs +++ b/src/problem/p2414_length_of_the_longest_alphabetical_continuous_substring.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -36,7 +35,13 @@ mod tests { #[test] fn test_2414() { - assert_eq!(2, Solution::longest_continuous_substring("abacaba".to_string())); - assert_eq!(5, Solution::longest_continuous_substring("abcde".to_string())); + assert_eq!( + 2, + Solution::longest_continuous_substring("abacaba".to_string()) + ); + assert_eq!( + 5, + Solution::longest_continuous_substring("abcde".to_string()) + ); } } diff --git a/src/problem/p242_valid_anagram.rs b/src/problem/p242_valid_anagram.rs index dfa4d51..56fe98a 100644 --- a/src/problem/p242_valid_anagram.rs +++ b/src/problem/p242_valid_anagram.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -25,7 +24,7 @@ impl Solution { if *value == 0 { map.remove(&c); } - }, + } None => { return false; } @@ -44,6 +43,9 @@ mod tests { #[test] fn test_242() { - assert!(Solution::is_anagram("anagram".to_owned(), "nagaram".to_owned())); + assert!(Solution::is_anagram( + "anagram".to_owned(), + "nagaram".to_owned() + )); } } diff --git a/src/problem/p2476_closest_nodes_queries_in_a_binary_search_tree.rs b/src/problem/p2476_closest_nodes_queries_in_a_binary_search_tree.rs index 5bc72b9..4336261 100644 --- a/src/problem/p2476_closest_nodes_queries_in_a_binary_search_tree.rs +++ b/src/problem/p2476_closest_nodes_queries_in_a_binary_search_tree.rs @@ -5,7 +5,7 @@ pub struct Solution {} use surf::url::UrlQuery; -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -27,8 +27,8 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn closest_nodes(root: Option>>, queries: Vec) -> Vec> { let mut array = Vec::new(); @@ -55,7 +55,7 @@ impl Solution { match pos { Ok(pos) => { result.push(vec![array[pos], array[pos]]); - }, + } Err(pos) => { if pos == 0 { result.push(vec![-1, array[pos]]); @@ -79,6 +79,5 @@ mod tests { use super::*; #[test] - fn test_2476() { - } + fn test_2476() {} } diff --git a/src/problem/p2516_take_k_of_each_character_from_left_and_right.rs b/src/problem/p2516_take_k_of_each_character_from_left_and_right.rs index 632b2a2..427b387 100644 --- a/src/problem/p2516_take_k_of_each_character_from_left_and_right.rs +++ b/src/problem/p2516_take_k_of_each_character_from_left_and_right.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -19,16 +18,16 @@ impl Solution { 'b' => left_counts[1] += 1, 'c' => left_counts[2] += 1, _ => unreachable!(), - } + } } if left_counts.iter().any(|x| *x < k) { return -1; } - + let mut result = n; let mut right = 0; - + // 左指针从右往左移动 for left in (0..=n - 1).rev() { while left_counts.iter().any(|x| *x < k) { @@ -36,19 +35,19 @@ impl Solution { 'a' => left_counts[0] += 1, 'b' => left_counts[1] += 1, 'c' => left_counts[2] += 1, - _ => unreachable!() + _ => unreachable!(), }; right += 1; } result = result.min(left + 1 + right); - + match s[left] { 'a' => left_counts[0] -= 1, 'b' => left_counts[1] -= 1, 'c' => left_counts[2] -= 1, - _ => unreachable!() + _ => unreachable!(), }; } diff --git a/src/problem/p2535_difference_between_element_sum_and_digit_sum_of_an_array.rs b/src/problem/p2535_difference_between_element_sum_and_digit_sum_of_an_array.rs index 44d3d37..16a0b1e 100644 --- a/src/problem/p2535_difference_between_element_sum_and_digit_sum_of_an_array.rs +++ b/src/problem/p2535_difference_between_element_sum_and_digit_sum_of_an_array.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p2549_count_distinct_numbers_on_board.rs b/src/problem/p2549_count_distinct_numbers_on_board.rs index cc686a9..a599c96 100644 --- a/src/problem/p2549_count_distinct_numbers_on_board.rs +++ b/src/problem/p2549_count_distinct_numbers_on_board.rs @@ -3,16 +3,11 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn distinct_integers(n: i32) -> i32 { - return if n == 1 { - 1 - } else { - n - 1 - }; + return if n == 1 { 1 } else { n - 1 }; } } @@ -23,6 +18,5 @@ mod tests { use super::*; #[test] - fn test_2549() { - } + fn test_2549() {} } diff --git a/src/problem/p2552_count_increasing_quadruplets.rs b/src/problem/p2552_count_increasing_quadruplets.rs index bdfa9a5..029fb52 100644 --- a/src/problem/p2552_count_increasing_quadruplets.rs +++ b/src/problem/p2552_count_increasing_quadruplets.rs @@ -3,32 +3,31 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn count_quadruplets(nums: Vec) -> i64 { let nums: Vec = nums.iter().map(|x| *x as usize).collect(); let n = nums.len(); - let mut pre = vec![0;n + 1]; + let mut pre = vec![0; n + 1]; let mut result = 0; - + for j in 0..n { let mut suffix = 0; - + for k in (j + 1..n).rev() { if nums[j] > nums[k] { result += pre[nums[k]] * suffix; - } else { + } else { suffix += 1; } } - + for i in nums[j] + 1..=n { pre[i] += 1; } } - + result } } @@ -41,6 +40,6 @@ mod tests { #[test] fn test_2552() { - assert_eq!(2, Solution::count_quadruplets(vec![1,3,2,4,5])); + assert_eq!(2, Solution::count_quadruplets(vec![1, 3, 2, 4, 5])); } } diff --git a/src/problem/p2555_maximize_win_from_two_segments.rs b/src/problem/p2555_maximize_win_from_two_segments.rs index 94b4a29..38eb8c7 100644 --- a/src/problem/p2555_maximize_win_from_two_segments.rs +++ b/src/problem/p2555_maximize_win_from_two_segments.rs @@ -3,13 +3,12 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn maximize_win(prize_positions: Vec, k: i32) -> i32 { let n = prize_positions.len(); - let mut dp = vec![0;n + 1]; + let mut dp = vec![0; n + 1]; let mut result = 0; for i in 0..n { @@ -21,7 +20,7 @@ impl Solution { result as i32 } - + fn binary_search(array: &Vec, target: i32) -> usize { let (mut left, mut right) = (0, array.len()); @@ -46,7 +45,7 @@ mod tests { #[test] fn test_2555() { - assert_eq!(7, Solution::maximize_win(vec![1,1,2,2,3,3,5], 2)); - assert_eq!(2, Solution::maximize_win(vec![1,2,3,4], 0)); + assert_eq!(7, Solution::maximize_win(vec![1, 1, 2, 2, 3, 3, 5], 2)); + assert_eq!(2, Solution::maximize_win(vec![1, 2, 3, 4], 0)); } } diff --git a/src/problem/p2575_find_the_divisibility_array_of_a_string.rs b/src/problem/p2575_find_the_divisibility_array_of_a_string.rs index c03579e..44ac86e 100644 --- a/src/problem/p2575_find_the_divisibility_array_of_a_string.rs +++ b/src/problem/p2575_find_the_divisibility_array_of_a_string.rs @@ -3,12 +3,11 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn divisibility_array(word: String, m: i32) -> Vec { - let mut result = vec![0;word.len()]; + let mut result = vec![0; word.len()]; let mut now = 0; let m = m as i64; @@ -23,7 +22,7 @@ impl Solution { now = now % m; } } - + result } } @@ -36,6 +35,9 @@ mod tests { #[test] fn test_2575() { - assert_eq!(vec![1,1,0,0,0,1], Solution::divisibility_array("998244".to_owned(), 3)); + assert_eq!( + vec![1, 1, 0, 0, 0, 1], + Solution::divisibility_array("998244".to_owned(), 3) + ); } } diff --git a/src/problem/p2576_find_the_maximum_number_of_marked_indices.rs b/src/problem/p2576_find_the_maximum_number_of_marked_indices.rs index 9073ae7..e7c1a97 100644 --- a/src/problem/p2576_find_the_maximum_number_of_marked_indices.rs +++ b/src/problem/p2576_find_the_maximum_number_of_marked_indices.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p2581_count_number_of_possible_root_nodes.rs b/src/problem/p2581_count_number_of_possible_root_nodes.rs index 5cc1659..3db96ad 100644 --- a/src/problem/p2581_count_number_of_possible_root_nodes.rs +++ b/src/problem/p2581_count_number_of_possible_root_nodes.rs @@ -5,14 +5,13 @@ use std::usize; */ pub struct Solution {} - // submission codes start here use std::collections::HashSet; impl Solution { pub fn root_count(edges: Vec>, guesses: Vec>, k: i32) -> i32 { - let mut graph = vec![vec![];edges.len() + 1]; + let mut graph = vec![vec![]; edges.len() + 1]; for edge in edges { let x = edge[0] as usize; @@ -24,19 +23,16 @@ impl Solution { let mut guess_set = HashSet::with_capacity(guesses.len()); for guess in guesses { - guess_set.insert(Solution::hash( - guess[0] as usize, - guess[1] as usize)); + guess_set.insert(Solution::hash(guess[0] as usize, guess[1] as usize)); } - + let mut count = 0; Solution::dfs(&graph, &guess_set, 0, usize::MAX, &mut count); dbg!(count); - + let mut result = 0; - Solution::tree_dp(&graph, &guess_set, &k, 0, - usize::MAX, count, &mut result); - + Solution::tree_dp(&graph, &guess_set, &k, 0, usize::MAX, count, &mut result); + result } @@ -44,7 +40,13 @@ impl Solution { (x as i64) * 1000000 + (y as i64) } - fn dfs(graph: &Vec>, guess_set: &HashSet, now: usize, pre: usize, count: &mut i32) { + fn dfs( + graph: &Vec>, + guess_set: &HashSet, + now: usize, + pre: usize, + count: &mut i32, + ) { for next in &graph[now] { let next = *next; if next == pre { @@ -59,8 +61,15 @@ impl Solution { } } - fn tree_dp(graph: &Vec>, guess_set: &HashSet, k: &i32, - now: usize, pre: usize, count: i32, result: &mut i32) { + fn tree_dp( + graph: &Vec>, + guess_set: &HashSet, + k: &i32, + now: usize, + pre: usize, + count: i32, + result: &mut i32, + ) { if count >= *k { *result += 1; } @@ -79,7 +88,7 @@ impl Solution { if guess_set.contains(&Solution::hash(next, now)) { count += 1; } - + Solution::tree_dp(graph, guess_set, k, next, now, count, result); } } @@ -95,12 +104,37 @@ mod tests { fn test_2581() { assert_eq!( Solution::root_count( - vec![vec![0,1],vec![1,2],vec![1,3],vec![4,2]], - vec![vec![1,3],vec![0,1],vec![1,0],vec![2,4]], 3), 3); + vec![vec![0, 1], vec![1, 2], vec![1, 3], vec![4, 2]], + vec![vec![1, 3], vec![0, 1], vec![1, 0], vec![2, 4]], + 3 + ), + 3 + ); assert_eq!( Solution::root_count( - vec![vec![0,1],vec![2,0],vec![0,3],vec![4,2],vec![3,5],vec![6,0],vec![1,7],vec![2,8],vec![2,9],vec![4,10],vec![9,11],vec![3,12],vec![13,8],vec![14,9],vec![15,9],vec![10,16]], - vec![vec![8,2],vec![12,3],vec![0,1],vec![16,10]], 2), 4); + vec![ + vec![0, 1], + vec![2, 0], + vec![0, 3], + vec![4, 2], + vec![3, 5], + vec![6, 0], + vec![1, 7], + vec![2, 8], + vec![2, 9], + vec![4, 10], + vec![9, 11], + vec![3, 12], + vec![13, 8], + vec![14, 9], + vec![15, 9], + vec![10, 16] + ], + vec![vec![8, 2], vec![12, 3], vec![0, 1], vec![16, 10]], + 2 + ), + 4 + ); } } diff --git a/src/problem/p2583_kth_largest_sum_in_a_binary_tree.rs b/src/problem/p2583_kth_largest_sum_in_a_binary_tree.rs index 53aa03b..019642c 100644 --- a/src/problem/p2583_kth_largest_sum_in_a_binary_tree.rs +++ b/src/problem/p2583_kth_largest_sum_in_a_binary_tree.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,8 +25,8 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn kth_largest_level_sum(root: Option>>, k: i32) -> i64 { let root = if let Some(r) = root { @@ -35,7 +35,7 @@ impl Solution { return -1; }; let k = k as usize; - + let mut levels = Vec::new(); let mut level = vec![root]; @@ -45,7 +45,7 @@ impl Solution { for node in level { sum += node.borrow().val as i64; - + if let Some(left) = &node.borrow().left { new_level.push(Rc::clone(left)); } @@ -75,6 +75,5 @@ mod tests { use super::*; #[test] - fn test_2583() { - } + fn test_2583() {} } diff --git a/src/problem/p2617_minimum_number_of_visited_cells_in_a_grid.rs b/src/problem/p2617_minimum_number_of_visited_cells_in_a_grid.rs index 5afeae8..5b8d0d9 100644 --- a/src/problem/p2617_minimum_number_of_visited_cells_in_a_grid.rs +++ b/src/problem/p2617_minimum_number_of_visited_cells_in_a_grid.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::{cmp::Reverse, collections::BinaryHeap}; @@ -12,16 +11,17 @@ impl Solution { let height = grid.len(); let width = grid[0].len(); - let mut column_heaps: Vec, usize)>> = vec![BinaryHeap::new(); width]; + let mut column_heaps: Vec, usize)>> = + vec![BinaryHeap::new(); width]; let mut row_heap: BinaryHeap<(Reverse, usize)> = BinaryHeap::new(); let mut dis = 0; - for (i, row) in grid.iter().enumerate() { + for (i, row) in grid.iter().enumerate() { row_heap.clear(); for (j, &node) in row.iter().enumerate() { while !row_heap.is_empty() && row_heap.peek().unwrap().1 < j { - row_heap.pop(); + row_heap.pop(); } let column_heap = &mut column_heaps[j]; @@ -29,11 +29,7 @@ impl Solution { column_heap.pop(); } - dis = if i > 0 || j > 0 { - i32::MAX - } else { - 1 - }; + dis = if i > 0 || j > 0 { i32::MAX } else { 1 }; if let Some((d, _)) = row_heap.peek() { dis = d.0 + 1; @@ -66,6 +62,5 @@ mod tests { use super::*; #[test] - fn test_2617() { - } + fn test_2617() {} } diff --git a/src/problem/p2641_cousins_in_binary_tree_ii.rs b/src/problem/p2641_cousins_in_binary_tree_ii.rs index ad3ca3a..88b46e5 100644 --- a/src/problem/p2641_cousins_in_binary_tree_ii.rs +++ b/src/problem/p2641_cousins_in_binary_tree_ii.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,10 +25,12 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { - pub fn replace_value_in_tree(root: Option>>) -> Option>> { + pub fn replace_value_in_tree( + root: Option>>, + ) -> Option>> { let root = if let Some(r) = root { r } else { @@ -76,7 +78,6 @@ impl Solution { queue = next_queue; } - root.borrow_mut().val = 0; Some(root) } @@ -90,8 +91,25 @@ mod tests { #[test] fn test_2641() { - assert_eq!(Solution::replace_value_in_tree(to_tree( - vec![Some(5),Some(4),Some(9),Some(1),Some(10),None,Some(7)])), - to_tree(vec![Some(0),Some(0),Some(0),Some(7),Some(7),None,Some(11)])); + assert_eq!( + Solution::replace_value_in_tree(to_tree(vec![ + Some(5), + Some(4), + Some(9), + Some(1), + Some(10), + None, + Some(7) + ])), + to_tree(vec![ + Some(0), + Some(0), + Some(0), + Some(7), + Some(7), + None, + Some(11) + ]) + ); } } diff --git a/src/problem/p2642_design_graph_with_shortest_path_calculator.rs b/src/problem/p2642_design_graph_with_shortest_path_calculator.rs index 93cf764..def12f2 100644 --- a/src/problem/p2642_design_graph_with_shortest_path_calculator.rs +++ b/src/problem/p2642_design_graph_with_shortest_path_calculator.rs @@ -57,7 +57,6 @@ impl Graph { queue.push((Reverse(distances[next]), next)); } } - } -1 diff --git a/src/problem/p2670_find_the_distinct_difference_array.rs b/src/problem/p2670_find_the_distinct_difference_array.rs index 7bc3611..b469dee 100644 --- a/src/problem/p2670_find_the_distinct_difference_array.rs +++ b/src/problem/p2670_find_the_distinct_difference_array.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -46,7 +45,9 @@ mod tests { #[test] fn test_2670() { - assert_eq!(Solution::distinct_difference_array(vec![1, 2, 3, 4, 5]), - vec![-3, -1, 1, 3, 5]); + assert_eq!( + Solution::distinct_difference_array(vec![1, 2, 3, 4, 5]), + vec![-3, -1, 1, 3, 5] + ); } } diff --git a/src/problem/p2671_frequency_tracker.rs b/src/problem/p2671_frequency_tracker.rs index fa76ece..7b6e94b 100644 --- a/src/problem/p2671_frequency_tracker.rs +++ b/src/problem/p2671_frequency_tracker.rs @@ -3,29 +3,26 @@ */ pub struct Solution {} - // submission codes start here use std::collections::{HashMap, HashSet}; struct FrequencyTracker { - number_map : HashMap, - frequency_map : HashMap>, + number_map: HashMap, + frequency_map: HashMap>, } - /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl FrequencyTracker { - fn new() -> Self { FrequencyTracker { number_map: HashMap::new(), frequency_map: HashMap::new(), } } - + fn add(&mut self, number: i32) { let mut entry = self.number_map.entry(number).or_insert(0); @@ -36,11 +33,10 @@ impl FrequencyTracker { } *entry += 1; - let set = self.frequency_map.entry(*entry) - .or_insert(HashSet::new()); + let set = self.frequency_map.entry(*entry).or_insert(HashSet::new()); set.insert(number); } - + fn delete_one(&mut self, number: i32) { if let Some(entry) = self.number_map.get_mut(&number) { if *entry == 0 { @@ -52,18 +48,17 @@ impl FrequencyTracker { } *entry -= 1; - let set = self.frequency_map.entry(*entry) - .or_insert(HashSet::new()); + let set = self.frequency_map.entry(*entry).or_insert(HashSet::new()); set.insert(number); - } + } } - + fn has_frequency(&self, frequency: i32) -> bool { let set = self.frequency_map.get(&frequency); match set { Some(set) => set.len() != 0, - None => false + None => false, } } } diff --git a/src/problem/p2673_make_costs_of_paths_equal_in_a_binary_tree.rs b/src/problem/p2673_make_costs_of_paths_equal_in_a_binary_tree.rs index 3b56d78..a683c54 100644 --- a/src/problem/p2673_make_costs_of_paths_equal_in_a_binary_tree.rs +++ b/src/problem/p2673_make_costs_of_paths_equal_in_a_binary_tree.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -35,6 +34,6 @@ mod tests { #[test] fn test_2673() { - assert_eq!(Solution::min_increments(7, vec![1,5,2,2,3,3,1]), 6); + assert_eq!(Solution::min_increments(7, vec![1, 5, 2, 2, 3, 3, 1]), 6); } } diff --git a/src/problem/p2697_lexicographically_smallest_palindrome.rs b/src/problem/p2697_lexicographically_smallest_palindrome.rs index 862c2c7..82e7b3b 100644 --- a/src/problem/p2697_lexicographically_smallest_palindrome.rs +++ b/src/problem/p2697_lexicographically_smallest_palindrome.rs @@ -41,7 +41,7 @@ pub struct Solution {} use std::cmp::min; impl Solution { pub fn make_smallest_palindrome(s: String) -> String { - let mut result : Vec = s.bytes().collect(); + let mut result: Vec = s.bytes().collect(); let mut left = 0; let mut right = result.len() - 1; @@ -69,11 +69,17 @@ mod tests { #[test] fn test_2697() { - assert_eq!(String::from("efcfe"), - Solution::make_smallest_palindrome(String::from("egcfe"))); - assert_eq!(String::from("abba"), - Solution::make_smallest_palindrome(String::from("abcd"))); - assert_eq!(String::from("neven"), - Solution::make_smallest_palindrome(String::from("seven"))); + assert_eq!( + String::from("efcfe"), + Solution::make_smallest_palindrome(String::from("egcfe")) + ); + assert_eq!( + String::from("abba"), + Solution::make_smallest_palindrome(String::from("abcd")) + ); + assert_eq!( + String::from("neven"), + Solution::make_smallest_palindrome(String::from("seven")) + ); } } diff --git a/src/problem/p26_remove_duplicates_from_sorted_array.rs b/src/problem/p26_remove_duplicates_from_sorted_array.rs index 44f483a..f33df7f 100644 --- a/src/problem/p26_remove_duplicates_from_sorted_array.rs +++ b/src/problem/p26_remove_duplicates_from_sorted_array.rs @@ -3,13 +3,12 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn remove_duplicates(nums: &mut Vec) -> i32 { let mut now = 1; - + for i in 1..nums.len() { if nums[i] != nums[i - 1] { nums[now] = nums[i]; @@ -28,6 +27,5 @@ mod tests { use super::*; #[test] - fn test_26() { - } + fn test_26() {} } diff --git a/src/problem/p2708_maximum_strength_of_a_group.rs b/src/problem/p2708_maximum_strength_of_a_group.rs index 71e2107..87f79ff 100644 --- a/src/problem/p2708_maximum_strength_of_a_group.rs +++ b/src/problem/p2708_maximum_strength_of_a_group.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -29,7 +28,7 @@ impl Solution { result *= r as i64; found = true; now += 2; - } else { + } else { now += 1; } } @@ -43,7 +42,7 @@ impl Solution { match found { true => result, - false => 0 + false => 0, } } } diff --git a/src/problem/p2719_count_of_integers.rs b/src/problem/p2719_count_of_integers.rs index 244b337..9d4a8af 100644 --- a/src/problem/p2719_count_of_integers.rs +++ b/src/problem/p2719_count_of_integers.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here struct DigitDP { @@ -12,12 +11,11 @@ struct DigitDP { min_sum: u32, max_sum: u32, - dp_vec : Vec> + dp_vec: Vec>, } impl DigitDP { - pub fn new(num1: Vec, num2: Vec, min_sum: u32, max_sum: u32) - -> DigitDP { + pub fn new(num1: Vec, num2: Vec, min_sum: u32, max_sum: u32) -> DigitDP { let mut dp = Vec::with_capacity(num2.len()); for _ in 0..num2.len() { @@ -33,7 +31,7 @@ impl DigitDP { num2, min_sum, max_sum, - dp_vec: dp + dp_vec: dp, } } @@ -43,24 +41,16 @@ impl DigitDP { 1 } else { 0 - } + }; } if !l_limit && !r_limit && self.dp_vec[index][sum as usize] != -1 { - return self.dp_vec[index][sum as usize] + return self.dp_vec[index][sum as usize]; } - let low = if l_limit { - self.num1[index] - } else { - 0 - }; + let low = if l_limit { self.num1[index] } else { 0 }; - let high = if r_limit { - self.num2[index] - } else { - 9 - }; + let high = if r_limit { self.num2[index] } else { 9 }; let mut result = 0; for i in low..=high { @@ -69,7 +59,7 @@ impl DigitDP { sum + i, i == self.num1[index] && l_limit, i == self.num2[index] && r_limit, - index + 1 + index + 1, ); if result > 1000000007 { @@ -83,7 +73,6 @@ impl DigitDP { result } - } impl Solution { @@ -96,19 +85,18 @@ impl Solution { num1.insert(0, 0); } - let mut digit_dp = DigitDP::new(num1, num2, - min_sum as u32, max_sum as u32); + let mut digit_dp = DigitDP::new(num1, num2, min_sum as u32, max_sum as u32); digit_dp.dp(0, true, true, 0) } - fn str_to_vec(num : String) -> Vec { + fn str_to_vec(num: String) -> Vec { let mut num_vec = Vec::new(); for c in num.chars() { match c.to_digit(10) { None => {} - Some(i) => {num_vec.push(i)} + Some(i) => num_vec.push(i), } } @@ -124,18 +112,14 @@ mod tests { #[test] fn test_2719() { - assert_eq!(Solution::count( - String::from("1"), - String::from("12"), - 1, - 8 - ), 11); + assert_eq!( + Solution::count(String::from("1"), String::from("12"), 1, 8), + 11 + ); - assert_eq!(Solution::count( - String::from("1"), - String::from("5"), - 1, + assert_eq!( + Solution::count(String::from("1"), String::from("5"), 1, 5), 5 - ), 5); + ); } } diff --git a/src/problem/p2744_find_maximum_number_of_string_pairs.rs b/src/problem/p2744_find_maximum_number_of_string_pairs.rs index 7db81c7..a96dd86 100644 --- a/src/problem/p2744_find_maximum_number_of_string_pairs.rs +++ b/src/problem/p2744_find_maximum_number_of_string_pairs.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -31,6 +30,5 @@ mod tests { use super::*; #[test] - fn test_2744() { - } + fn test_2744() {} } diff --git a/src/problem/p274_h_index.rs b/src/problem/p274_h_index.rs index 5e5740b..d6975cb 100644 --- a/src/problem/p274_h_index.rs +++ b/src/problem/p274_h_index.rs @@ -37,6 +37,6 @@ mod tests { #[test] fn test_274() { assert_eq!(3, Solution::h_index(vec![3, 0, 6, 1, 5])); - assert_eq!(1, Solution::h_index(vec![1,3,1])); + assert_eq!(1, Solution::h_index(vec![1, 3, 1])); } } diff --git a/src/problem/p2765_longest_alternating_subarray.rs b/src/problem/p2765_longest_alternating_subarray.rs index 86fc0e0..05fa215 100644 --- a/src/problem/p2765_longest_alternating_subarray.rs +++ b/src/problem/p2765_longest_alternating_subarray.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -32,9 +31,9 @@ mod tests { #[test] fn test_2765() { - assert_eq!(Solution::alternating_subarray(vec![2,3,4,3,4]), 4); - assert_eq!(Solution::alternating_subarray(vec![4,5,6]), 2); - assert_eq!(Solution::alternating_subarray(vec![21,9,5]), -1); - assert_eq!(Solution::alternating_subarray(vec![21,22]), 2); + assert_eq!(Solution::alternating_subarray(vec![2, 3, 4, 3, 4]), 4); + assert_eq!(Solution::alternating_subarray(vec![4, 5, 6]), 2); + assert_eq!(Solution::alternating_subarray(vec![21, 9, 5]), -1); + assert_eq!(Solution::alternating_subarray(vec![21, 22]), 2); } } diff --git a/src/problem/p2788_split_strings_by_separator.rs b/src/problem/p2788_split_strings_by_separator.rs index e9a722b..d8c0e86 100644 --- a/src/problem/p2788_split_strings_by_separator.rs +++ b/src/problem/p2788_split_strings_by_separator.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -33,6 +32,5 @@ mod tests { use super::*; #[test] - fn test_2788() { - } + fn test_2788() {} } diff --git a/src/problem/p2789_largest_element_in_an_array_after_merge_operations.rs b/src/problem/p2789_largest_element_in_an_array_after_merge_operations.rs index 59ee64c..8e95fe6 100644 --- a/src/problem/p2789_largest_element_in_an_array_after_merge_operations.rs +++ b/src/problem/p2789_largest_element_in_an_array_after_merge_operations.rs @@ -3,23 +3,20 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn max_array_value(nums: Vec) -> i64 { - let mut nums: Vec = nums.iter() - .map(|x| *x as i64) - .collect(); + let mut nums: Vec = nums.iter().map(|x| *x as i64).collect(); - let mut result = nums[0]; - for i in (0..(nums.len() - 1)).rev() { - if nums[i] <= nums[i + 1] { - nums[i] = nums[i] + nums[i + 1]; + let mut result = nums[0]; + for i in (0..(nums.len() - 1)).rev() { + if nums[i] <= nums[i + 1] { + nums[i] = nums[i] + nums[i + 1]; - result = result.max(nums[i]); - } + result = result.max(nums[i]); } + } result } @@ -33,7 +30,7 @@ mod tests { #[test] fn test_2789() { - assert_eq!(21, Solution::max_array_value(vec![2,3,7,9,3])); - assert_eq!(11, Solution::max_array_value(vec![5,3,3])); + assert_eq!(21, Solution::max_array_value(vec![2, 3, 7, 9, 3])); + assert_eq!(11, Solution::max_array_value(vec![5, 3, 3])); } } diff --git a/src/problem/p27_remove_element.rs b/src/problem/p27_remove_element.rs index 71d0de7..072ad05 100644 --- a/src/problem/p27_remove_element.rs +++ b/src/problem/p27_remove_element.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -40,7 +39,7 @@ mod tests { #[test] fn test_27() { - let mut array = vec![3,2,2,3]; + let mut array = vec![3, 2, 2, 3]; assert_eq!(2, Solution::remove_element(&mut array, 3)); for i in 0..2 { assert_eq!(2, array[i]); diff --git a/src/problem/p2808_minimum_seconds_to_equalize_a_circular_array.rs b/src/problem/p2808_minimum_seconds_to_equalize_a_circular_array.rs index c3c9862..2cc5477 100644 --- a/src/problem/p2808_minimum_seconds_to_equalize_a_circular_array.rs +++ b/src/problem/p2808_minimum_seconds_to_equalize_a_circular_array.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -41,7 +40,7 @@ mod tests { #[test] fn test_2808() { - assert_eq!(Solution::minimum_seconds(vec![1,2,1,2]), 1); - assert_eq!(Solution::minimum_seconds(vec![2,1,3,3,2]), 2); + assert_eq!(Solution::minimum_seconds(vec![1, 2, 1, 2]), 1); + assert_eq!(Solution::minimum_seconds(vec![2, 1, 3, 3, 2]), 2); } } diff --git a/src/problem/p2809_minimum_time_to_make_array_sum_at_most_x.rs b/src/problem/p2809_minimum_time_to_make_array_sum_at_most_x.rs index e573ae9..e671e32 100644 --- a/src/problem/p2809_minimum_time_to_make_array_sum_at_most_x.rs +++ b/src/problem/p2809_minimum_time_to_make_array_sum_at_most_x.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here struct Pair { @@ -55,11 +54,11 @@ mod tests { #[test] fn test_2809() { - assert_eq!(Solution::minimum_time(vec![1, 2, 3], vec![1, 2, 3], 4), - 3); - assert_eq!(Solution::minimum_time(vec![1, 2, 3], vec![3, 3, 3], 4), - -1); - assert_eq!(Solution::minimum_time(vec![4, 4, 9, 10], vec![4, 4, 1, 3], 16), - 4); + assert_eq!(Solution::minimum_time(vec![1, 2, 3], vec![1, 2, 3], 4), 3); + assert_eq!(Solution::minimum_time(vec![1, 2, 3], vec![3, 3, 3], 4), -1); + assert_eq!( + Solution::minimum_time(vec![4, 4, 9, 10], vec![4, 4, 1, 3], 16), + 4 + ); } } diff --git a/src/problem/p2828_check_if_a_string_is_an_acronym_of_words.rs b/src/problem/p2828_check_if_a_string_is_an_acronym_of_words.rs index eaecc18..f088692 100644 --- a/src/problem/p2828_check_if_a_string_is_an_acronym_of_words.rs +++ b/src/problem/p2828_check_if_a_string_is_an_acronym_of_words.rs @@ -3,27 +3,27 @@ * * Given an array of strings words and a string s, determine if s is an acronym of words. * The string s is considered an acronym of words if it can be formed by concatenating the first character of each string in words in order. For example, "ab" can be formed from ["apple", "banana"], but it can't be formed from ["bear", "aardvark"]. - * Return true if s is an acronym of words, and false otherwise. + * Return true if s is an acronym of words, and false otherwise. * * Example 1: * * Input: words = ["alice","bob","charlie"], s = "abc" * Output: true - * Explanation: The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c', respectively. Hence, s = "abc" is the acronym. + * Explanation: The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c', respectively. Hence, s = "abc" is the acronym. * * Example 2: * * Input: words = ["an","apple"], s = "a" * Output: false - * Explanation: The first character in the words "an" and "apple" are 'a' and 'a', respectively. - * The acronym formed by concatenating these characters is "aa". + * Explanation: The first character in the words "an" and "apple" are 'a' and 'a', respectively. + * The acronym formed by concatenating these characters is "aa". * Hence, s = "a" is not the acronym. * * Example 3: * * Input: words = ["never","gonna","give","up","on","you"], s = "ngguoy" * Output: true - * Explanation: By concatenating the first character of the words in the array, we get the string "ngguoy". + * Explanation: By concatenating the first character of the words in the array, we get the string "ngguoy". * Hence, s = "ngguoy" is the acronym. * * @@ -66,13 +66,24 @@ mod tests { #[test] fn test_2828() { - assert_eq!(true, Solution::is_acronym(vec![ - String::from("alice"), - String::from("bob"), - String::from("charlie")], String::from("abc"))); + assert_eq!( + true, + Solution::is_acronym( + vec![ + String::from("alice"), + String::from("bob"), + String::from("charlie") + ], + String::from("abc") + ) + ); - assert_eq!(false, Solution::is_acronym(vec![ - String::from("an"), - String::from("apple")], String::from("a"))); + assert_eq!( + false, + Solution::is_acronym( + vec![String::from("an"), String::from("apple")], + String::from("a") + ) + ); } } diff --git a/src/problem/p2834_find_the_minimum_possible_sum_of_a_beautiful_array.rs b/src/problem/p2834_find_the_minimum_possible_sum_of_a_beautiful_array.rs index 5ada853..b54c368 100644 --- a/src/problem/p2834_find_the_minimum_possible_sum_of_a_beautiful_array.rs +++ b/src/problem/p2834_find_the_minimum_possible_sum_of_a_beautiful_array.rs @@ -3,22 +3,20 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn minimum_possible_sum(n: i32, target: i32) -> i32 { let n = n as i64; let target = target as i64; let m = 1e9 as i64 + 7; - + let length = target / 2; if length >= n { - ((1 + n ) * n / 2 % m ) as i32 + ((1 + n) * n / 2 % m) as i32 } else { - (((1 + length) * length / 2 - + (target + target + n - length - 1) * (n - length) / 2) % m) - as i32 + (((1 + length) * length / 2 + (target + target + n - length - 1) * (n - length) / 2) + % m) as i32 } } } diff --git a/src/problem/p2846_minimum_edge_weight_equilibrium_queries_in_a_tree.rs b/src/problem/p2846_minimum_edge_weight_equilibrium_queries_in_a_tree.rs index 811e9ab..894916e 100644 --- a/src/problem/p2846_minimum_edge_weight_equilibrium_queries_in_a_tree.rs +++ b/src/problem/p2846_minimum_edge_weight_equilibrium_queries_in_a_tree.rs @@ -3,13 +3,12 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; struct UnionFind { - parents : Vec + parents: Vec, } impl UnionFind { @@ -20,9 +19,7 @@ impl UnionFind { parents.push(i); } - UnionFind { - parents - } + UnionFind { parents } } fn find(&mut self, x: usize) -> usize { @@ -42,14 +39,14 @@ impl UnionFind { struct Tree { matrix: Vec>, // 从节点0到节点i上权值为j边的个数 - count : Vec>, + count: Vec>, length: usize, // tarjan算法辅助数组 - least_common_ancestor : Vec, + least_common_ancestor: Vec, // (i, x) 表示边,y 是least_common_ancestor的下标 query_edges: Vec>, uf: UnionFind, - visited : Vec + visited: Vec, } impl Tree { @@ -60,7 +57,7 @@ impl Tree { for _ in 0..=n { matrix.push(HashMap::new()); - count.push(vec![0;27]) + count.push(vec![0; 27]) } for edge in edges { @@ -78,7 +75,7 @@ impl Tree { least_common_ancestor: vec![0; queries.len()], query_edges: vec![vec![]; n], uf: UnionFind::new(n), - visited: vec![false; n] + visited: vec![false; n], }; for (index, query) in queries.iter().enumerate() { @@ -91,7 +88,7 @@ impl Tree { tree } - fn tarjan(&mut self, node : usize, parent : usize) { + fn tarjan(&mut self, node: usize, parent: usize) { // 顺便构建count数组 if node != 0 { self.count[node] = self.count[parent].clone(); @@ -114,7 +111,7 @@ impl Tree { for (target, index) in &self.query_edges[node] { if *target != node && !self.visited[*target] { - continue + continue; } self.least_common_ancestor[*index] = self.uf.find(*target); @@ -125,7 +122,11 @@ impl Tree { } impl Solution { - pub fn min_operations_queries(n: i32, edges: Vec>, queries: Vec>) -> Vec { + pub fn min_operations_queries( + n: i32, + edges: Vec>, + queries: Vec>, + ) -> Vec { let mut tree = Tree::new(n, edges, &queries); tree.tarjan(0, 0); @@ -136,7 +137,8 @@ impl Solution { let (x, y) = (query[0] as usize, query[1] as usize); for i in 1..=26 { - let t = tree.count[x][i] + tree.count[y][i] - 2 * tree.count[tree.least_common_ancestor[index]][i]; + let t = tree.count[x][i] + tree.count[y][i] + - 2 * tree.count[tree.least_common_ancestor[index]][i]; max_count = max_count.max(t); total += t; } @@ -156,17 +158,20 @@ mod tests { #[test] fn test_2846() { - assert_eq!(Solution::min_operations_queries(7, - vec![vec![0, 1, 1], - vec![1, 2, 1], - vec![2, 3, 1], - vec![3, 4, 2], - vec![4, 5, 2], - vec![5, 6, 2]], - vec![vec![0, 3], - vec![3, 6], - vec![2, 6], - vec![0, 6]]), - vec![0, 0, 1, 3]) + assert_eq!( + Solution::min_operations_queries( + 7, + vec![ + vec![0, 1, 1], + vec![1, 2, 1], + vec![2, 3, 1], + vec![3, 4, 2], + vec![4, 5, 2], + vec![5, 6, 2] + ], + vec![vec![0, 3], vec![3, 6], vec![2, 6], vec![0, 6]] + ), + vec![0, 0, 1, 3] + ) } } diff --git a/src/problem/p2848_points_that_intersect_with_cars.rs b/src/problem/p2848_points_that_intersect_with_cars.rs index 973b716..6174e67 100644 --- a/src/problem/p2848_points_that_intersect_with_cars.rs +++ b/src/problem/p2848_points_that_intersect_with_cars.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -36,8 +35,14 @@ mod tests { #[test] fn test_2848() { - assert_eq!(7, Solution::number_of_points(vec![vec![3, 6], vec![1, 5], vec![4, 7]])); + assert_eq!( + 7, + Solution::number_of_points(vec![vec![3, 6], vec![1, 5], vec![4, 7]]) + ); assert_eq!(7, Solution::number_of_points(vec![vec![1, 3], vec![5, 8]])); - assert_eq!(8, Solution::number_of_points(vec![vec![4, 4], vec![9, 10], vec![9, 10], vec![3, 8]])); + assert_eq!( + 8, + Solution::number_of_points(vec![vec![4, 4], vec![9, 10], vec![9, 10], vec![3, 8]]) + ); } } diff --git a/src/problem/p2859_sum_of_values_at_indices_with_k_set_bits.rs b/src/problem/p2859_sum_of_values_at_indices_with_k_set_bits.rs index 04c01db..8b17721 100644 --- a/src/problem/p2859_sum_of_values_at_indices_with_k_set_bits.rs +++ b/src/problem/p2859_sum_of_values_at_indices_with_k_set_bits.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -41,9 +40,18 @@ mod tests { #[test] fn test_2859() { - assert_eq!(Solution::sum_indices_with_k_set_bits(vec![5,10,1,5,2], 1), 13); - assert_eq!(Solution::sum_indices_with_k_set_bits(vec![4,3,2,1], 2), 1); + assert_eq!( + Solution::sum_indices_with_k_set_bits(vec![5, 10, 1, 5, 2], 1), + 13 + ); + assert_eq!( + Solution::sum_indices_with_k_set_bits(vec![4, 3, 2, 1], 2), + 1 + ); assert_eq!(Solution::sum_indices_with_k_set_bits(vec![1], 0), 1); - assert_eq!(Solution::sum_indices_with_k_set_bits(vec![1,1,3,1,6], 2), 1); + assert_eq!( + Solution::sum_indices_with_k_set_bits(vec![1, 1, 3, 1, 6], 2), + 1 + ); } } diff --git a/src/problem/p2860_happy_students.rs b/src/problem/p2860_happy_students.rs index 627a474..256e6c7 100644 --- a/src/problem/p2860_happy_students.rs +++ b/src/problem/p2860_happy_students.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -13,17 +12,17 @@ impl Solution { nums.sort(); // 是否能不选中任何学生 - let mut result = 0; + let mut result = 0; for i in 0..=n { if i > 0 && nums[i - 1] >= i { continue; - } - + } + if i < n && nums[i] <= i { continue; } - + result += 1; } diff --git a/src/problem/p2861_maximum_number_of_alloys.rs b/src/problem/p2861_maximum_number_of_alloys.rs index 066b351..7d47fda 100644 --- a/src/problem/p2861_maximum_number_of_alloys.rs +++ b/src/problem/p2861_maximum_number_of_alloys.rs @@ -3,11 +3,17 @@ */ pub struct Solution {} - // submission codes start here impl Solution { - fn check(n: usize, count: i32, budget: i32, composition: &Vec, stock: &Vec, cost: &Vec) -> bool { + fn check( + n: usize, + count: i32, + budget: i32, + composition: &Vec, + stock: &Vec, + cost: &Vec, + ) -> bool { let mut need = 0i64; for i in 0..n { @@ -21,14 +27,20 @@ impl Solution { need <= budget as i64 } - pub fn max_number_of_alloys(n: i32, k: i32, budget: i32, - composition: Vec>, stock: Vec, cost: Vec) -> i32 { + pub fn max_number_of_alloys( + n: i32, + k: i32, + budget: i32, + composition: Vec>, + stock: Vec, + cost: Vec, + ) -> i32 { let mut result = 0; let (n, k) = (n as usize, k as usize); for m in 0..k { let mut left = 0; - let mut right = vec![0;n]; + let mut right = vec![0; n]; for i in 0..n { right[i] = (stock[i] + budget / cost[i]) / composition[m][i]; @@ -66,10 +78,16 @@ mod tests { #[test] fn test_2861() { - assert_eq!(Solution::max_number_of_alloys(3,2,15, - vec![vec![1,1,1], vec![1,1,10]], - vec![0,0,0], - vec![1,2,3]), - 2); + assert_eq!( + Solution::max_number_of_alloys( + 3, + 2, + 15, + vec![vec![1, 1, 1], vec![1, 1, 10]], + vec![0, 0, 0], + vec![1, 2, 3] + ), + 2 + ); } } diff --git a/src/problem/p2864_maximum_odd_binary_number.rs b/src/problem/p2864_maximum_odd_binary_number.rs index 249e953..fe41889 100644 --- a/src/problem/p2864_maximum_odd_binary_number.rs +++ b/src/problem/p2864_maximum_odd_binary_number.rs @@ -3,14 +3,11 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn maximum_odd_binary_number(s: String) -> String { - let nums: Vec = s.chars() - .map(|c| c.to_digit(10).unwrap()) - .collect(); + let nums: Vec = s.chars().map(|c| c.to_digit(10).unwrap()).collect(); let mut one_count = 0; let mut zero_count = 0; @@ -25,7 +22,7 @@ impl Solution { let mut result: Vec = Vec::with_capacity(nums.len()); - for _ in 1..one_count { + for _ in 1..one_count { result.push('1'); } @@ -47,6 +44,9 @@ mod tests { #[test] fn test_2864() { assert_eq!("001", Solution::maximum_odd_binary_number("010".to_owned())); - assert_eq!("1001", Solution::maximum_odd_binary_number("0101".to_owned())); + assert_eq!( + "1001", + Solution::maximum_odd_binary_number("0101".to_owned()) + ); } } diff --git a/src/problem/p2865_beautiful_towers_i.rs b/src/problem/p2865_beautiful_towers_i.rs index 6868803..efe7d27 100644 --- a/src/problem/p2865_beautiful_towers_i.rs +++ b/src/problem/p2865_beautiful_towers_i.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -12,7 +11,7 @@ impl Solution { for peek in 0..max_heights.len() { let mut total_height = max_heights[peek] as i64; - let mut heights = vec![0;max_heights.len()]; + let mut heights = vec![0; max_heights.len()]; heights[peek] = max_heights[peek]; for i in (0..peek).rev() { @@ -28,7 +27,6 @@ impl Solution { result = result.max(total_height); } - result } } @@ -41,8 +39,8 @@ mod tests { #[test] fn test_2865() { - assert_eq!(Solution::maximum_sum_of_heights(vec![5,3,4,1,1]), 13); - assert_eq!(Solution::maximum_sum_of_heights(vec![6,5,3,9,2,6]), 22); - assert_eq!(Solution::maximum_sum_of_heights(vec![3,2,5,5,2,3]), 18); + assert_eq!(Solution::maximum_sum_of_heights(vec![5, 3, 4, 1, 1]), 13); + assert_eq!(Solution::maximum_sum_of_heights(vec![6, 5, 3, 9, 2, 6]), 22); + assert_eq!(Solution::maximum_sum_of_heights(vec![3, 2, 5, 5, 2, 3]), 18); } } diff --git a/src/problem/p2867_count_valid_paths_in_a_tree.rs b/src/problem/p2867_count_valid_paths_in_a_tree.rs index a4b51be..04254a0 100644 --- a/src/problem/p2867_count_valid_paths_in_a_tree.rs +++ b/src/problem/p2867_count_valid_paths_in_a_tree.rs @@ -3,32 +3,36 @@ */ pub struct Solution {} - // submission codes start here impl Solution { - fn dfs(graph: &Vec>, primes: &Vec, seen: &mut Vec, - i: usize, pre: usize) { + fn dfs( + graph: &Vec>, + primes: &Vec, + seen: &mut Vec, + i: usize, + pre: usize, + ) { seen.push(i); for next in &graph[i] { let next = *next; if next != pre && !primes[next] { Solution::dfs(graph, primes, seen, next, i); - } + } } } pub fn count_paths(n: i32, edges: Vec>) -> i64 { let n = n as usize; - let mut primes = vec![true;n + 1]; + let mut primes = vec![true; n + 1]; primes[1] = false; for i in 2..=n { if primes[i] { if i * i > n { continue; } - + for j in (i * i..=n).step_by(i) { primes[j] = false; } @@ -36,7 +40,7 @@ impl Solution { } primes = dbg!(primes); - let mut graph = vec![vec![];n + 1]; + let mut graph = vec![vec![]; n + 1]; for edge in edges { let x = edge[0] as usize; let y = edge[1] as usize; @@ -52,19 +56,19 @@ impl Solution { if !primes[root] { continue; } - + let mut current = 0; for i in &graph[root] { let i = *i; if (primes[i]) { continue; } - + if count[i] == 0 { let mut seen = Vec::new(); Solution::dfs(&graph, &primes, &mut seen, i, 0); for k in &seen { - count[*k] = seen.len() as i64; + count[*k] = seen.len() as i64; } } @@ -87,7 +91,12 @@ mod tests { #[test] fn test_2867() { - assert_eq!(6, Solution::count_paths(6, - vec![vec![1,2],vec![1,3],vec![2,4],vec![3,5],vec![3,6]])); + assert_eq!( + 6, + Solution::count_paths( + 6, + vec![vec![1, 2], vec![1, 3], vec![2, 4], vec![3, 5], vec![3, 6]] + ) + ); } } diff --git a/src/problem/p289_game_of_life.rs b/src/problem/p289_game_of_life.rs index 0bc665f..a955583 100644 --- a/src/problem/p289_game_of_life.rs +++ b/src/problem/p289_game_of_life.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -11,12 +10,21 @@ impl Solution { let m = board.len(); let n = board[0].len(); - let directions = vec![(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0)]; + let directions = vec![ + (-1, -1), + (0, -1), + (1, -1), + (1, 0), + (1, 1), + (0, 1), + (-1, 1), + (-1, 0), + ]; for i in 0..m { for j in 0..n { let mut count = 0; - + for (delta_x, delta_y) in directions.iter() { let x = i as i32 + *delta_x; let y = j as i32 + *delta_y; @@ -68,6 +76,5 @@ mod tests { use super::*; #[test] - fn test_289() { - } + fn test_289() {} } diff --git a/src/problem/p28_find_the_index_of_the_first_occurrence_in_a_string.rs b/src/problem/p28_find_the_index_of_the_first_occurrence_in_a_string.rs index a0d8c7d..686a47b 100644 --- a/src/problem/p28_find_the_index_of_the_first_occurrence_in_a_string.rs +++ b/src/problem/p28_find_the_index_of_the_first_occurrence_in_a_string.rs @@ -3,14 +3,13 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn str_str(haystack: String, needle: String) -> i32 { - match haystack.find(&needle) { + match haystack.find(&needle) { Some(pos) => pos as i32, - None => -1 + None => -1, } } } @@ -22,6 +21,5 @@ mod tests { use super::*; #[test] - fn test_28() { - } + fn test_28() {} } diff --git a/src/problem/p2908_minimum_sum_of_mountain_triplets_i.rs b/src/problem/p2908_minimum_sum_of_mountain_triplets_i.rs index 301fa87..6011036 100644 --- a/src/problem/p2908_minimum_sum_of_mountain_triplets_i.rs +++ b/src/problem/p2908_minimum_sum_of_mountain_triplets_i.rs @@ -3,14 +3,12 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn minimum_sum(nums: Vec) -> i32 { let mut result = i32::MAX; - for j in 1..nums.len() - 1 { let mut first = i32::MAX; @@ -35,11 +33,7 @@ impl Solution { result = result.min(first + nums[j] + last); } - return if result == i32::MAX { - -1 - } else { - result - }; + return if result == i32::MAX { -1 } else { result }; } } @@ -51,6 +45,6 @@ mod tests { #[test] fn test_2908() { - assert_eq!(9, Solution::minimum_sum(vec![8,6,1,5,3])); + assert_eq!(9, Solution::minimum_sum(vec![8, 6, 1, 5, 3])); } } diff --git a/src/problem/p290_word_pattern.rs b/src/problem/p290_word_pattern.rs index 49eb065..c24684e 100644 --- a/src/problem/p290_word_pattern.rs +++ b/src/problem/p290_word_pattern.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -14,7 +13,7 @@ impl Solution { if words.len() != pattern.len() { return false; } - + let mut map = HashMap::new(); let mut reverse_map = HashMap::new(); @@ -23,7 +22,7 @@ impl Solution { if *entry != word { return false; - } + } let entry = reverse_map.entry(word).or_insert(c); @@ -44,6 +43,9 @@ mod tests { #[test] fn test_290() { - assert!(Solution::word_pattern("abba".to_owned(), "dog cat cat dog".to_owned())); + assert!(Solution::word_pattern( + "abba".to_owned(), + "dog cat cat dog".to_owned() + )); } } diff --git a/src/problem/p2917_find_the_k_or_of_an_array.rs b/src/problem/p2917_find_the_k_or_of_an_array.rs index b69ad1c..7e0df26 100644 --- a/src/problem/p2917_find_the_k_or_of_an_array.rs +++ b/src/problem/p2917_find_the_k_or_of_an_array.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -38,6 +37,6 @@ mod tests { #[test] fn test_2917() { - assert_eq!(9, Solution::find_k_or(vec![7,12,9,8,9,15], 4)); + assert_eq!(9, Solution::find_k_or(vec![7, 12, 9, 8, 9, 15], 4)); } } diff --git a/src/problem/p292_nim_game.rs b/src/problem/p292_nim_game.rs index 8d5af7d..faec19e 100644 --- a/src/problem/p292_nim_game.rs +++ b/src/problem/p292_nim_game.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p295_find_median_from_data_stream.rs b/src/problem/p295_find_median_from_data_stream.rs index 24c124e..c61bfc3 100644 --- a/src/problem/p295_find_median_from_data_stream.rs +++ b/src/problem/p295_find_median_from_data_stream.rs @@ -9,35 +9,33 @@ use std::{cmp::Reverse, collections::BinaryHeap}; #[derive(Debug)] struct MedianFinder { left: BinaryHeap, - right: BinaryHeap> + right: BinaryHeap>, } - /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl MedianFinder { - fn new() -> Self { Self { left: BinaryHeap::new(), - right: BinaryHeap::new() + right: BinaryHeap::new(), } } - + fn add_num(&mut self, num: i32) { // 保证如下的状态 // left.len = right.len + 1 // left.len = right.len - + if self.left.len() > self.right.len() { // 此时左边必然有数 let left_peek = *self.left.peek().unwrap(); - + if num >= left_peek { self.right.push(Reverse(num)) - } else { + } else { self.right.push(Reverse(left_peek)); self.left.pop(); self.left.push(num); @@ -46,13 +44,13 @@ impl MedianFinder { // 判空 if self.left.is_empty() { self.left.push(num); - } else { + } else { // 此时必然两端都有数 let right_peek = self.right.peek().unwrap().0; - + if num <= right_peek { self.left.push(num); - } else { + } else { self.left.push(right_peek); self.right.pop(); self.right.push(Reverse(num)); @@ -60,13 +58,13 @@ impl MedianFinder { } } } - + fn find_median(&self) -> f64 { return if self.left.len() == self.right.len() { (*self.left.peek().unwrap() as f64 + self.right.peek().unwrap().0 as f64) / 2f64 - } else { + } else { *self.left.peek().unwrap() as f64 - } + }; } } @@ -86,15 +84,15 @@ mod tests { #[test] fn test_295() { let mut finder = MedianFinder::new(); - + finder.add_num(1); finder.add_num(2); - + assert_eq!(1.5, finder.find_median()); - + finder.add_num(3); finder = dbg!(finder); - + assert_eq!(2f64, finder.find_median()); } } diff --git a/src/problem/p299_bulls_and_cows.rs b/src/problem/p299_bulls_and_cows.rs index 4ba8c60..0950d13 100644 --- a/src/problem/p299_bulls_and_cows.rs +++ b/src/problem/p299_bulls_and_cows.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -49,7 +48,13 @@ mod tests { #[test] fn test_299() { - assert_eq!("1A3B", Solution::get_hint("1807".to_owned(), "7810".to_owned())); - assert_eq!("1A1B", Solution::get_hint("1123".to_owned(), "0111".to_owned())); + assert_eq!( + "1A3B", + Solution::get_hint("1807".to_owned(), "7810".to_owned()) + ); + assert_eq!( + "1A1B", + Solution::get_hint("1123".to_owned(), "0111".to_owned()) + ); } } diff --git a/src/problem/p2_add_two_numbers.rs b/src/problem/p2_add_two_numbers.rs index 1c03014..4877421 100644 --- a/src/problem/p2_add_two_numbers.rs +++ b/src/problem/p2_add_two_numbers.rs @@ -9,27 +9,27 @@ * Input: l1 = [2,4,3], l2 = [5,6,4] * Output: [7,0,8] * Explanation: 342 + 465 = 807. - * + * * Example 2: - * + * * Input: l1 = [0], l2 = [0] * Output: [0] - * + * * Example 3: - * + * * Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] * Output: [8,9,9,9,0,0,0,1] - * + * * * Constraints: - * + * * The number of nodes in each linked list is in the range [1, 100]. * 0 <= Node.val <= 9 * It is guaranteed that the list represents a number that does not have leading zeros. - * + * */ pub struct Solution {} -use crate::util::linked_list::{ListNode, to_list}; +use crate::util::linked_list::{to_list, ListNode}; // problem: https://leetcode.cn/problems/add-two-numbers/ // discuss: https://leetcode.cn/problems/add-two-numbers/discuss/?currentPage=1&orderBy=most_votes&query= @@ -53,8 +53,10 @@ use crate::util::linked_list::{ListNode, to_list}; // } // } impl Solution { - pub fn add_two_numbers(l1: Option>, l2: Option>) - -> Option> { + pub fn add_two_numbers( + l1: Option>, + l2: Option>, + ) -> Option> { let (mut left, mut right) = (l1, l2); let mut dummy_head = Some(Box::new(ListNode::new(0))); let mut now = &mut dummy_head; @@ -62,13 +64,11 @@ impl Solution { loop { if left.is_none() && right.is_none() && overflow == 0 { - break + break; } let left_value = match left { - None => { - 0 - } + None => 0, Some(node) => { left = node.next; node.val @@ -76,9 +76,7 @@ impl Solution { }; let right_value = match right { - None => { - 0 - } + None => 0, Some(node) => { right = node.next; node.val diff --git a/src/problem/p3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k.rs b/src/problem/p3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k.rs index c77ba99..67b41c9 100644 --- a/src/problem/p3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k.rs +++ b/src/problem/p3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -12,36 +11,36 @@ impl Solution { while left < right { let middle = (left + right + 1) / 2; - + if Self::accumulate_price(x, middle) > k { right = middle - 1; } else { left = middle; } } - + left } - + fn accumulate_price(x: i32, num: i64) -> i64 { let mut result = 0; let length = 64 - i64::leading_zeros(num) as i32; - + for i in (x..=length).step_by(x as usize) { result += Self::accumulate_bit_price(i, num); } - + result } - + fn accumulate_bit_price(x: i32, num: i64) -> i64 { let period = 1i64 << x; let mut result = period / 2 * (num / period); - + if num % period >= period / 2 { result += num % period - (period / 2 - 1); } - + result } } diff --git a/src/problem/p300_longest_increasing_subsequence.rs b/src/problem/p300_longest_increasing_subsequence.rs index ffb2c84..90bf7c1 100644 --- a/src/problem/p300_longest_increasing_subsequence.rs +++ b/src/problem/p300_longest_increasing_subsequence.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -12,16 +11,16 @@ impl Solution { if n == 0 { return 0; } - + let mut length = 1; - let mut dp = vec![0;n + 1]; + let mut dp = vec![0; n + 1]; dp[length] = nums[0]; - + for i in 1..n { if nums[i] > dp[length] { length += 1; dp[length] = nums[i]; - } else { + } else { // 二分查找dp中小于nums[i]的位置 let (mut left, mut right, mut pos) = (1, length, 0); while left <= right { @@ -29,15 +28,15 @@ impl Solution { if dp[middle] < nums[i] { pos = middle; left = middle + 1; - } else { + } else { right = middle - 1; } } - + dp[pos + 1] = nums[i]; } } - + length as i32 } } @@ -49,7 +48,5 @@ mod tests { use super::*; #[test] - fn test_300() { - - } + fn test_300() {} } diff --git a/src/problem/p30_substring_with_concatenation_of_all_words.rs b/src/problem/p30_substring_with_concatenation_of_all_words.rs index 7621a2a..a8277d7 100644 --- a/src/problem/p30_substring_with_concatenation_of_all_words.rs +++ b/src/problem/p30_substring_with_concatenation_of_all_words.rs @@ -77,9 +77,12 @@ mod tests { #[test] fn test_30() { - assert_eq!(vec![0,9], Solution::find_substring("barfoothefoobarman".to_owned(), vec![ - "foo".to_owned(), - "bar".to_owned() - ])) + assert_eq!( + vec![0, 9], + Solution::find_substring( + "barfoothefoobarman".to_owned(), + vec!["foo".to_owned(), "bar".to_owned()] + ) + ) } } diff --git a/src/problem/p310_minimum_height_trees.rs b/src/problem/p310_minimum_height_trees.rs index d12a659..6600711 100644 --- a/src/problem/p310_minimum_height_trees.rs +++ b/src/problem/p310_minimum_height_trees.rs @@ -3,14 +3,13 @@ */ pub struct Solution {} - // submission codes start here use std::collections::VecDeque; impl Solution { pub fn find_min_height_trees(n: i32, edges: Vec>) -> Vec { let n = n as usize; - let mut graph = vec![vec![];n]; + let mut graph = vec![vec![]; n]; for edge in &edges { let x = edge[0] as usize; @@ -20,7 +19,7 @@ impl Solution { graph[y].push(x); } - let mut parents = vec![usize::MAX;n]; + let mut parents = vec![usize::MAX; n]; let x = Solution::find_longest_node(0, &mut parents, &graph); let mut y = Solution::find_longest_node(x, &mut parents, &graph); @@ -46,7 +45,7 @@ impl Solution { let n = graph.len(); let mut queue = VecDeque::with_capacity(n); - let mut visited = vec![false;n]; + let mut visited = vec![false; n]; queue.push_back(node); visited[node] = true; @@ -64,7 +63,7 @@ impl Solution { queue.push_back(next); } } - } + } result } @@ -78,6 +77,9 @@ mod tests { #[test] fn test_310() { - assert_eq!(vec![1], Solution::find_min_height_trees(4, vec![vec![1,0], vec![1,2], vec![1,3]])); + assert_eq!( + vec![1], + Solution::find_min_height_trees(4, vec![vec![1, 0], vec![1, 2], vec![1, 3]]) + ); } } diff --git a/src/problem/p3117_minimum_sum_of_values_by_dividing_array.rs b/src/problem/p3117_minimum_sum_of_values_by_dividing_array.rs index bdb372d..6050a7e 100644 --- a/src/problem/p3117_minimum_sum_of_values_by_dividing_array.rs +++ b/src/problem/p3117_minimum_sum_of_values_by_dividing_array.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -22,8 +21,14 @@ impl Solution { } } - fn dfs(memory: &mut Vec>, i: usize, j: usize, current: i32, - nums: &Vec, and_values: &Vec) -> i32 { + fn dfs( + memory: &mut Vec>, + i: usize, + j: usize, + current: i32, + nums: &Vec, + and_values: &Vec, + ) -> i32 { let (n, m) = (nums.len(), and_values.len()); let key = m * i + j; @@ -44,7 +49,8 @@ impl Solution { let mut result = Self::dfs(memory, i + 1, j, current, nums, and_values); if current == and_values[j] { - result = result.min(Self::dfs(memory, i + 1, j + 1, INFINITE, nums, and_values) + nums[i]); + result = + result.min(Self::dfs(memory, i + 1, j + 1, INFINITE, nums, and_values) + nums[i]); } memory[key].insert(current, result); @@ -60,6 +66,9 @@ mod tests { #[test] fn test_3117() { - assert_eq!(12, Solution::minimum_value_sum(vec![1, 4, 3, 3, 2], vec![0, 3, 3, 2])); + assert_eq!( + 12, + Solution::minimum_value_sum(vec![1, 4, 3, 3, 2], vec![0, 3, 3, 2]) + ); } } diff --git a/src/problem/p3127_make_a_square_with_the_same_color.rs b/src/problem/p3127_make_a_square_with_the_same_color.rs index 15670a1..b004f72 100644 --- a/src/problem/p3127_make_a_square_with_the_same_color.rs +++ b/src/problem/p3127_make_a_square_with_the_same_color.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here const DELTA: [(usize, usize); 4] = [(0, 0), (0, 1), (1, 0), (1, 1)]; @@ -11,10 +10,10 @@ const DELTA: [(usize, usize); 4] = [(0, 0), (0, 1), (1, 0), (1, 1)]; impl Solution { pub fn can_make_square(grid: Vec>) -> bool { for i in 0..2 { - for j in 0.. 2 { + for j in 0..2 { let mut white: i32 = 0; let mut black: i32 = 0; - + for (x, y) in DELTA { match grid[i + x][j + y] { 'B' => black += 1, @@ -22,13 +21,13 @@ impl Solution { _ => {} } } - + if white.abs_diff(black) == 2 || white.abs_diff(black) == 4 { return true; } } } - + false } } @@ -40,6 +39,5 @@ mod tests { use super::*; #[test] - fn test_3127() { - } + fn test_3127() {} } diff --git a/src/problem/p3133_minimum_array_end.rs b/src/problem/p3133_minimum_array_end.rs index 79e293c..a0d49ed 100644 --- a/src/problem/p3133_minimum_array_end.rs +++ b/src/problem/p3133_minimum_array_end.rs @@ -3,28 +3,27 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn min_end(n: i32, x: i32) -> i64 { let (n, x) = (n as i64, x as i64); let mut result = x; - + let bit_count = 128 - n.leading_zeros() - x.leading_zeros(); - + let mut pos = 0; - + for i in 0..bit_count { if (result >> i) & 1 == 0 { if ((n - 1) >> pos) & 1 == 1 { result |= 1 << i; } - + pos += 1; } } - + result } } diff --git a/src/problem/p3134_find_the_median_of_the_uniqueness_array.rs b/src/problem/p3134_find_the_median_of_the_uniqueness_array.rs index ea0a3a8..7b1ff5f 100644 --- a/src/problem/p3134_find_the_median_of_the_uniqueness_array.rs +++ b/src/problem/p3134_find_the_median_of_the_uniqueness_array.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; diff --git a/src/problem/p3137_minimum_number_of_operations_to_make_word_k_periodic.rs b/src/problem/p3137_minimum_number_of_operations_to_make_word_k_periodic.rs index d62da4e..7bb2a70 100644 --- a/src/problem/p3137_minimum_number_of_operations_to_make_word_k_periodic.rs +++ b/src/problem/p3137_minimum_number_of_operations_to_make_word_k_periodic.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -22,7 +21,6 @@ impl Solution { result = result.min((n / k) as i32 - *entry); } - result } @@ -36,6 +34,9 @@ mod tests { #[test] fn test_3137() { - assert_eq!(1, Solution::minimum_operations_to_make_k_periodic("leetcodeleet".to_owned(), 4)); + assert_eq!( + 1, + Solution::minimum_operations_to_make_k_periodic("leetcodeleet".to_owned(), 4) + ); } } diff --git a/src/problem/p3142_check_if_grid_satisfies_conditions.rs b/src/problem/p3142_check_if_grid_satisfies_conditions.rs index 3f779b1..3e4ea5d 100644 --- a/src/problem/p3142_check_if_grid_satisfies_conditions.rs +++ b/src/problem/p3142_check_if_grid_satisfies_conditions.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -34,9 +33,19 @@ mod tests { #[test] fn test_3142() { - assert!(Solution::satisfies_conditions(vec![vec![1, 0, 2], vec![1, 0, 2]])); - assert!(!Solution::satisfies_conditions(vec![vec![1, 1, 1], vec![0, 0, 0]])); + assert!(Solution::satisfies_conditions(vec![ + vec![1, 0, 2], + vec![1, 0, 2] + ])); + assert!(!Solution::satisfies_conditions(vec![ + vec![1, 1, 1], + vec![0, 0, 0] + ])); assert!(Solution::satisfies_conditions(vec![vec![0]])); - assert!(!Solution::satisfies_conditions(vec![vec![1], vec![2], vec![3]])); + assert!(!Solution::satisfies_conditions(vec![ + vec![1], + vec![2], + vec![3] + ])); } } diff --git a/src/problem/p3144_minimum_substring_partition_of_equal_character_frequency.rs b/src/problem/p3144_minimum_substring_partition_of_equal_character_frequency.rs index 24da6e6..d16471a 100644 --- a/src/problem/p3144_minimum_substring_partition_of_equal_character_frequency.rs +++ b/src/problem/p3144_minimum_substring_partition_of_equal_character_frequency.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -11,26 +10,26 @@ impl Solution { pub fn minimum_substrings_in_partition(s: String) -> i32 { let s: Vec = s.chars().collect(); let n = s.len(); - - let mut dp = vec![i32::MAX;n + 1]; + + let mut dp = vec![i32::MAX; n + 1]; let mut char_count = HashMap::new(); dp[0] = 0; - + for i in 1..=n { let mut max_count = 0; char_count.clear(); - + for j in (1..=i).rev() { let entry = char_count.entry(s[j - 1]).or_insert(0); *entry += 1; max_count = max_count.max(*entry); - + if max_count * char_count.len() == i - j + 1 && dp[j - 1] != i32::MAX { dp[i] = dp[i].min(dp[j - 1] + 1); } } } - + dp[n] } } @@ -43,7 +42,13 @@ mod tests { #[test] fn test_3144() { - assert_eq!(3, Solution::minimum_substrings_in_partition("fabccddg".to_owned())); - assert_eq!(2, Solution::minimum_substrings_in_partition("abababaccddb".to_owned())); + assert_eq!( + 3, + Solution::minimum_substrings_in_partition("fabccddg".to_owned()) + ); + assert_eq!( + 2, + Solution::minimum_substrings_in_partition("abababaccddb".to_owned()) + ); } } diff --git a/src/problem/p3145_find_products_of_elements_of_big_array.rs b/src/problem/p3145_find_products_of_elements_of_big_array.rs index 9a0ade3..1a6e136 100644 --- a/src/problem/p3145_find_products_of_elements_of_big_array.rs +++ b/src/problem/p3145_find_products_of_elements_of_big_array.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -88,7 +87,7 @@ impl Solution { result + sum } - /// 计算小于等于x所有数的数位对幂的贡献之和 + /// 计算小于等于x所有数的数位对幂的贡献之和 fn count_power(x: i64) -> i64 { let mut result = 0; let mut sum = 0; @@ -133,7 +132,13 @@ mod tests { #[test] fn test_3145() { - assert_eq!(vec![4], Solution::find_products_of_elements(vec![vec![1, 3, 7]])); - assert_eq!(vec![2, 2], Solution::find_products_of_elements(vec![vec![2, 5, 3], vec![7, 7, 4]])); + assert_eq!( + vec![4], + Solution::find_products_of_elements(vec![vec![1, 3, 7]]) + ); + assert_eq!( + vec![2, 2], + Solution::find_products_of_elements(vec![vec![2, 5, 3], vec![7, 7, 4]]) + ); } } diff --git a/src/problem/p3146_permutation_difference_between_two_strings.rs b/src/problem/p3146_permutation_difference_between_two_strings.rs index 93f5d2c..fbc4e62 100644 --- a/src/problem/p3146_permutation_difference_between_two_strings.rs +++ b/src/problem/p3146_permutation_difference_between_two_strings.rs @@ -3,26 +3,25 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; impl Solution { pub fn find_permutation_difference(s: String, t: String) -> i32 { let mut map = HashMap::new(); - + for (i, c) in s.chars().enumerate() { map.insert(c, i as i32); } - + let mut result = 0; - + for (i, c) in t.chars().enumerate() { let target = map.get(&c).unwrap(); - + result += (i as i32 - *target).abs() } - + result } } @@ -35,6 +34,9 @@ mod tests { #[test] fn test_3146() { - assert_eq!(2, Solution::find_permutation_difference("abc".to_owned(), "bac".to_owned())); + assert_eq!( + 2, + Solution::find_permutation_difference("abc".to_owned(), "bac".to_owned()) + ); } } diff --git a/src/problem/p3153_sum_of_digit_differences_of_all_pairs.rs b/src/problem/p3153_sum_of_digit_differences_of_all_pairs.rs index c8a8c21..111ddf4 100644 --- a/src/problem/p3153_sum_of_digit_differences_of_all_pairs.rs +++ b/src/problem/p3153_sum_of_digit_differences_of_all_pairs.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -23,11 +22,11 @@ impl Solution { map[digit] += 1; } - result += map.iter().filter_map(|x| if *x == 0 { - None - } else { - Some(*x * (n - *x)) - }).sum::() / 2; + result += map + .iter() + .filter_map(|x| if *x == 0 { None } else { Some(*x * (n - *x)) }) + .sum::() + / 2; base *= 10; } diff --git a/src/problem/p3154_find_number_of_ways_to_reach_the_k_th_stair.rs b/src/problem/p3154_find_number_of_ways_to_reach_the_k_th_stair.rs index f52ace6..a554d55 100644 --- a/src/problem/p3154_find_number_of_ways_to_reach_the_k_th_stair.rs +++ b/src/problem/p3154_find_number_of_ways_to_reach_the_k_th_stair.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -16,28 +15,28 @@ impl Solution { if pos - n - 1 <= k && k <= pos { result += Self::combine(n + 1, pos - k); } - + if pos - n - 1 > k { break; } - + n += 1; pos *= 2; } - + result } /// C_n^k = \frac{n * (n - 1) * .. * (n - k + 1)}{1 * 2 * 3 * ... * k} - fn combine(n : i32, k: i32) -> i32 { + fn combine(n: i32, k: i32) -> i32 { let mut result: i64 = 1; let (n, k) = (n as i64, k as i64); - + for i in (n - k + 1..=n).rev() { result *= i; - result /= n - i + 1; + result /= n - i + 1; } - + result as i32 } } diff --git a/src/problem/p3158_find_the_xor_of_numbers_which_appear_twice.rs b/src/problem/p3158_find_the_xor_of_numbers_which_appear_twice.rs index 3ad56f4..19e12ac 100644 --- a/src/problem/p3158_find_the_xor_of_numbers_which_appear_twice.rs +++ b/src/problem/p3158_find_the_xor_of_numbers_which_appear_twice.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p3162_find_the_number_of_good_pairs_i.rs b/src/problem/p3162_find_the_number_of_good_pairs_i.rs index e4f0fae..23445cb 100644 --- a/src/problem/p3162_find_the_number_of_good_pairs_i.rs +++ b/src/problem/p3162_find_the_number_of_good_pairs_i.rs @@ -3,18 +3,14 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn number_of_pairs(nums1: Vec, nums2: Vec, k: i32) -> i32 { - let nums1: Vec = nums1.into_iter().filter_map(|x| { - if x % k == 0 { - Some(x / k) - } else { - None - } - }).collect(); + let nums1: Vec = nums1 + .into_iter() + .filter_map(|x| if x % k == 0 { Some(x / k) } else { None }) + .collect(); let mut result = 0; @@ -38,8 +34,14 @@ mod tests { #[test] fn test_3162() { - assert_eq!(5, Solution::number_of_pairs(vec![1, 3, 4], vec![1, 3, 4], 1)); - assert_eq!(2, Solution::number_of_pairs(vec![1, 2, 4, 12], vec![2, 4], 3)); + assert_eq!( + 5, + Solution::number_of_pairs(vec![1, 3, 4], vec![1, 3, 4], 1) + ); + assert_eq!( + 2, + Solution::number_of_pairs(vec![1, 2, 4, 12], vec![2, 4], 3) + ); assert_eq!(1, Solution::number_of_pairs(vec![2, 12], vec![4, 3], 4)); } } diff --git a/src/problem/p3164_find_the_number_of_good_pairs_ii.rs b/src/problem/p3164_find_the_number_of_good_pairs_ii.rs index 0c78ba0..b020dd5 100644 --- a/src/problem/p3164_find_the_number_of_good_pairs_ii.rs +++ b/src/problem/p3164_find_the_number_of_good_pairs_ii.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -53,7 +52,13 @@ mod tests { #[test] fn test_3164() { - assert_eq!(5, Solution::number_of_pairs(vec![1, 3, 4], vec![1, 3, 4], 1)); - assert_eq!(2, Solution::number_of_pairs(vec![1, 2, 4, 12], vec![2, 4], 3)); + assert_eq!( + 5, + Solution::number_of_pairs(vec![1, 3, 4], vec![1, 3, 4], 1) + ); + assert_eq!( + 2, + Solution::number_of_pairs(vec![1, 2, 4, 12], vec![2, 4], 3) + ); } } diff --git a/src/problem/p3171_find_subarray_with_bitwise_or_closest_to_k.rs b/src/problem/p3171_find_subarray_with_bitwise_or_closest_to_k.rs index 81b7e40..ef48af0 100644 --- a/src/problem/p3171_find_subarray_with_bitwise_or_closest_to_k.rs +++ b/src/problem/p3171_find_subarray_with_bitwise_or_closest_to_k.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::cmp::Ordering; @@ -28,12 +27,10 @@ impl Solution { } } - pos_to_bit.sort_by(|a, b| { - match b.0.cmp(&a.0) { - Ordering::Less => { Ordering::Less } - Ordering::Equal => { b.1.cmp(&a.1) } - Ordering::Greater => { Ordering::Greater } - } + pos_to_bit.sort_by(|a, b| match b.0.cmp(&a.0) { + Ordering::Less => Ordering::Less, + Ordering::Equal => b.1.cmp(&a.1), + Ordering::Greater => Ordering::Greater, }); let mut value = 0; diff --git a/src/problem/p3174_clear_digits.rs b/src/problem/p3174_clear_digits.rs index ea0f55e..d12e2cd 100644 --- a/src/problem/p3174_clear_digits.rs +++ b/src/problem/p3174_clear_digits.rs @@ -3,19 +3,18 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn clear_digits(s: String) -> String { let s: Vec = s.chars().collect(); let mut mark = vec![true; s.len()]; - + for (i, &c) in s.iter().enumerate() { if !c.is_ascii_digit() { continue; } - + // 是数字 mark[i] = false; let mut last = i - 1; @@ -25,14 +24,11 @@ impl Solution { } mark[last] = false; } - - s.iter().enumerate().filter_map(|(i, &c)| { - if mark[i] { - Some(c) - } else { - None - } - }).collect() + + s.iter() + .enumerate() + .filter_map(|(i, &c)| if mark[i] { Some(c) } else { None }) + .collect() } } diff --git a/src/problem/p3175_find_the_first_player_to_win_k_games_in_a_row.rs b/src/problem/p3175_find_the_first_player_to_win_k_games_in_a_row.rs new file mode 100644 index 0000000..c6d45b7 --- /dev/null +++ b/src/problem/p3175_find_the_first_player_to_win_k_games_in_a_row.rs @@ -0,0 +1,45 @@ +/** + * [3175] Find The First Player to win K Games in a Row + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn find_winning_player(skills: Vec, k: i32) -> i32 { + let n = skills.len(); + let k = k as usize; + let mut pos = 0; + + for i in 1..n { + if skills[i] > skills[pos] { + pos = i; + } + if pos == 0 { + if i - pos >= k { + break; + } + } else { + if i - pos >= k - 1 { + break; + } + } + } + + pos as i32 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3175() { + assert_eq!(1, Solution::find_winning_player(vec![1, 6, 17], 1)); + assert_eq!(2, Solution::find_winning_player(vec![4, 2, 6, 3, 9], 2)); + assert_eq!(1, Solution::find_winning_player(vec![2, 5, 4], 3)); + } +} diff --git a/src/problem/p3176_find_the_maximum_length_of_a_good_subsequence_i.rs b/src/problem/p3176_find_the_maximum_length_of_a_good_subsequence_i.rs index 2a39805..81cdade 100644 --- a/src/problem/p3176_find_the_maximum_length_of_a_good_subsequence_i.rs +++ b/src/problem/p3176_find_the_maximum_length_of_a_good_subsequence_i.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -36,6 +35,6 @@ mod tests { #[test] fn test_3176() { assert_eq!(4, Solution::maximum_length(vec![1, 2, 1, 1, 3], 2)); - assert_eq!(2, Solution::maximum_length(vec![1,2,3,4,5,1], 0)); + assert_eq!(2, Solution::maximum_length(vec![1, 2, 3, 4, 5, 1], 0)); } } diff --git a/src/problem/p3177_find_the_maximum_length_of_a_good_subsequence_ii.rs b/src/problem/p3177_find_the_maximum_length_of_a_good_subsequence_ii.rs index 6b6c77f..2911e9b 100644 --- a/src/problem/p3177_find_the_maximum_length_of_a_good_subsequence_ii.rs +++ b/src/problem/p3177_find_the_maximum_length_of_a_good_subsequence_ii.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -34,6 +33,5 @@ mod tests { use super::*; #[test] - fn test_3177() { - } + fn test_3177() {} } diff --git a/src/problem/p3184_count_pairs_that_form_a_complete_day_i.rs b/src/problem/p3184_count_pairs_that_form_a_complete_day_i.rs index 7fd4e67..0ea761d 100644 --- a/src/problem/p3184_count_pairs_that_form_a_complete_day_i.rs +++ b/src/problem/p3184_count_pairs_that_form_a_complete_day_i.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -35,6 +34,9 @@ mod tests { #[test] fn test_3184() { assert_eq!(3, Solution::count_complete_day_pairs(vec![72, 48, 24, 3])); - assert_eq!(2, Solution::count_complete_day_pairs(vec![12, 12, 30, 24, 24])); + assert_eq!( + 2, + Solution::count_complete_day_pairs(vec![12, 12, 30, 24, 24]) + ); } } diff --git a/src/problem/p3185_count_pairs_that_form_a_complete_day_ii.rs b/src/problem/p3185_count_pairs_that_form_a_complete_day_ii.rs index 4cc936b..81371ac 100644 --- a/src/problem/p3185_count_pairs_that_form_a_complete_day_ii.rs +++ b/src/problem/p3185_count_pairs_that_form_a_complete_day_ii.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -22,7 +21,7 @@ impl Solution { *entry += 1; } - result + result } } @@ -34,7 +33,10 @@ mod tests { #[test] fn test_3185() { - assert_eq!(2, Solution::count_complete_day_pairs(vec![12, 12, 30, 24, 24])); + assert_eq!( + 2, + Solution::count_complete_day_pairs(vec![12, 12, 30, 24, 24]) + ); assert_eq!(3, Solution::count_complete_day_pairs(vec![72, 48, 24, 3])); } } diff --git a/src/problem/p3191_minimum_operations_to_make_binary_array_elements_equal_to_one_i.rs b/src/problem/p3191_minimum_operations_to_make_binary_array_elements_equal_to_one_i.rs index 3f22e2b..fe4fd2d 100644 --- a/src/problem/p3191_minimum_operations_to_make_binary_array_elements_equal_to_one_i.rs +++ b/src/problem/p3191_minimum_operations_to_make_binary_array_elements_equal_to_one_i.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -39,11 +38,7 @@ impl Solution { } fn reverse(pos: usize, nums: &mut Vec) { - nums[pos] = if nums[pos] == 1 { - 0 - } else { - 1 - } + nums[pos] = if nums[pos] == 1 { 0 } else { 1 } } } diff --git a/src/problem/p3192_minimum_operations_to_make_binary_array_elements_equal_to_one_ii.rs b/src/problem/p3192_minimum_operations_to_make_binary_array_elements_equal_to_one_ii.rs index 8d98804..d8cb326 100644 --- a/src/problem/p3192_minimum_operations_to_make_binary_array_elements_equal_to_one_ii.rs +++ b/src/problem/p3192_minimum_operations_to_make_binary_array_elements_equal_to_one_ii.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p3193_count_the_number_of_inversions.rs b/src/problem/p3193_count_the_number_of_inversions.rs index ec46902..2ee59c6 100644 --- a/src/problem/p3193_count_the_number_of_inversions.rs +++ b/src/problem/p3193_count_the_number_of_inversions.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -36,7 +35,12 @@ impl Solution { } } - fn dfs(end: usize, count: usize, requirements: &HashMap, dp: &mut Vec>) -> i32 { + fn dfs( + end: usize, + count: usize, + requirements: &HashMap, + dp: &mut Vec>, + ) -> i32 { if end == 0 { return 1; } @@ -75,8 +79,17 @@ mod tests { #[test] fn test_3193() { assert_eq!(1, Solution::number_of_permutations(2, vec![vec![1, 1]])); - assert_eq!(2, Solution::number_of_permutations(3, vec![vec![2, 2], vec![0, 0]])); - assert_eq!(1, Solution::number_of_permutations(3, vec![vec![2, 2], vec![1, 1], vec![0, 0]])); - assert_eq!(1, Solution::number_of_permutations(2, vec![vec![0, 0], vec![1, 0]])); + assert_eq!( + 2, + Solution::number_of_permutations(3, vec![vec![2, 2], vec![0, 0]]) + ); + assert_eq!( + 1, + Solution::number_of_permutations(3, vec![vec![2, 2], vec![1, 1], vec![0, 0]]) + ); + assert_eq!( + 1, + Solution::number_of_permutations(2, vec![vec![0, 0], vec![1, 0]]) + ); } } diff --git a/src/problem/p3194_minimum_average_of_smallest_and_largest_elements.rs b/src/problem/p3194_minimum_average_of_smallest_and_largest_elements.rs index ce1a6b4..a2a5562 100644 --- a/src/problem/p3194_minimum_average_of_smallest_and_largest_elements.rs +++ b/src/problem/p3194_minimum_average_of_smallest_and_largest_elements.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -30,7 +29,10 @@ mod tests { #[test] fn test_3194() { - assert_eq!(5.5, Solution::minimum_average(vec![7, 8, 3, 4, 15, 13, 4, 1])); + assert_eq!( + 5.5, + Solution::minimum_average(vec![7, 8, 3, 4, 15, 13, 4, 1]) + ); assert_eq!(5.5, Solution::minimum_average(vec![1, 9, 8, 3, 10, 5])); assert_eq!(5.0, Solution::minimum_average(vec![1, 2, 3, 7, 8, 9])); } diff --git a/src/problem/p3200_maximum_height_of_a_triangle.rs b/src/problem/p3200_maximum_height_of_a_triangle.rs index 9d6774b..73cc013 100644 --- a/src/problem/p3200_maximum_height_of_a_triangle.rs +++ b/src/problem/p3200_maximum_height_of_a_triangle.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p322_coin_change.rs b/src/problem/p322_coin_change.rs index 77b99de..4374a36 100644 --- a/src/problem/p322_coin_change.rs +++ b/src/problem/p322_coin_change.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -37,7 +36,7 @@ mod tests { #[test] fn test_322() { - assert_eq!(3, Solution::coin_change(vec![1,2,5], 11)); + assert_eq!(3, Solution::coin_change(vec![1, 2, 5], 11)); assert_eq!(-1, Solution::coin_change(vec![2], 3)); assert_eq!(0, Solution::coin_change(vec![1], 0)); } diff --git a/src/problem/p331_verify_preorder_serialization_of_a_binary_tree.rs b/src/problem/p331_verify_preorder_serialization_of_a_binary_tree.rs index b098284..31562cb 100644 --- a/src/problem/p331_verify_preorder_serialization_of_a_binary_tree.rs +++ b/src/problem/p331_verify_preorder_serialization_of_a_binary_tree.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -44,7 +43,9 @@ mod tests { #[test] fn test_331() { - assert!(Solution::is_valid_serialization(String::from("9,3,4,#,#,1,#,#,2,#,6,#,#"))); + assert!(Solution::is_valid_serialization(String::from( + "9,3,4,#,#,1,#,#,2,#,6,#,#" + ))); assert!(!Solution::is_valid_serialization(String::from("1,#"))); assert!(!Solution::is_valid_serialization(String::from("9,#,#,1"))); } diff --git a/src/problem/p33_search_in_rotated_sorted_array.rs b/src/problem/p33_search_in_rotated_sorted_array.rs index e0b05ff..ff675d0 100644 --- a/src/problem/p33_search_in_rotated_sorted_array.rs +++ b/src/problem/p33_search_in_rotated_sorted_array.rs @@ -3,45 +3,40 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn search(nums: Vec, target: i32) -> i32 { if nums.len() == 1 { - return if target == nums[0] { - 0 - } else { - -1 - }; + return if target == nums[0] { 0 } else { -1 }; } - + let (mut left, mut right) = (0, nums.len()); while left < right { let middle = (right - left) / 2 + left; - + if nums[middle] == target { return middle as i32; } - + if nums[middle] > nums[0] { // 左侧的数组是有序的 if target >= nums[0] && target < nums[middle] { right = middle; - } else { + } else { left = middle + 1; } - } else { + } else { // 右侧数组是有序的 if target > nums[middle] && target <= nums[nums.len() - 1] { left = middle + 1; - } else { + } else { right = middle; } } } - + -1 } } @@ -53,6 +48,5 @@ mod tests { use super::*; #[test] - fn test_33() { - } + fn test_33() {} } diff --git a/src/problem/p34_find_first_and_last_position_of_element_in_sorted_array.rs b/src/problem/p34_find_first_and_last_position_of_element_in_sorted_array.rs index db51e80..fd76c00 100644 --- a/src/problem/p34_find_first_and_last_position_of_element_in_sorted_array.rs +++ b/src/problem/p34_find_first_and_last_position_of_element_in_sorted_array.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -44,7 +43,7 @@ impl Solution { } } -// submission codes end +// submission codes end #[cfg(test)] mod tests { @@ -52,9 +51,12 @@ mod tests { #[test] fn test_34() { - assert_eq!(vec![3, 4], Solution::search_range(vec![5, 7, 7, 8, 8, 10], 8)); + assert_eq!( + vec![3, 4], + Solution::search_range(vec![5, 7, 7, 8, 8, 10], 8) + ); assert_eq!(vec![-1, -1], Solution::search_range(vec![2, 2], 3)); assert_eq!(vec![0, 0], Solution::search_range(vec![1], 1)); assert_eq!(vec![0, 1], Solution::search_range(vec![2, 2], 2)); - } + } } diff --git a/src/problem/p35_search_insert_position.rs b/src/problem/p35_search_insert_position.rs index e1c007a..062e5ac 100644 --- a/src/problem/p35_search_insert_position.rs +++ b/src/problem/p35_search_insert_position.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -37,6 +36,5 @@ mod tests { use super::*; #[test] - fn test_35() { - } + fn test_35() {} } diff --git a/src/problem/p365_water_and_jug_problem.rs b/src/problem/p365_water_and_jug_problem.rs index 61cc9b1..32c05b4 100644 --- a/src/problem/p365_water_and_jug_problem.rs +++ b/src/problem/p365_water_and_jug_problem.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -42,6 +41,6 @@ mod tests { fn test_365() { assert!(Solution::can_measure_water(3, 5, 4)); assert!(!Solution::can_measure_water(2, 6, 5)); - assert!(Solution::can_measure_water(1,2,3)); + assert!(Solution::can_measure_water(1, 2, 3)); } } diff --git a/src/problem/p373_find_k_pairs_with_smallest_sums.rs b/src/problem/p373_find_k_pairs_with_smallest_sums.rs index 3909a88..7b9deb6 100644 --- a/src/problem/p373_find_k_pairs_with_smallest_sums.rs +++ b/src/problem/p373_find_k_pairs_with_smallest_sums.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::cmp::Ordering; @@ -17,19 +16,14 @@ struct Pair<'a> { impl Pair<'_> { fn new<'a>(nums1: &'a Vec, nums2: &'a Vec, x: usize, y: usize) -> Pair<'a> { - Pair { - nums1, - nums2, - x, - y, - } + Pair { nums1, nums2, x, y } } } impl Ord for Pair<'_> { fn cmp(&self, other: &Self) -> Ordering { - (other.nums1[other.x] + other.nums2[other.y]).cmp( - &(self.nums1[self.x] + self.nums2[self.y])) + (other.nums1[other.x] + other.nums2[other.y]) + .cmp(&(self.nums1[self.x] + self.nums2[self.y])) } } @@ -67,7 +61,6 @@ impl Solution { count += 1; } - result.iter().map(|(x, y)| vec![*x, *y]).collect() } } @@ -80,7 +73,9 @@ mod tests { #[test] fn test_373() { - assert_eq!(vec![vec![1, 2], vec![1, 4], vec![1, 6]], - Solution::k_smallest_pairs(vec![1, 7, 11], vec![2, 4, 6], 3)); + assert_eq!( + vec![vec![1, 2], vec![1, 4], vec![1, 6]], + Solution::k_smallest_pairs(vec![1, 7, 11], vec![2, 4, 6], 3) + ); } } diff --git a/src/problem/p380_insert_delete_getrandom_o1.rs b/src/problem/p380_insert_delete_getrandom_o1.rs index 8f63ed2..ff09126 100644 --- a/src/problem/p380_insert_delete_getrandom_o1.rs +++ b/src/problem/p380_insert_delete_getrandom_o1.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use rand::{rngs::ThreadRng, Rng}; use std::collections::HashMap; @@ -12,25 +11,23 @@ struct RandomizedSet { array: Vec, pos_table: HashMap, pos_now: usize, - rng: ThreadRng + rng: ThreadRng, } - /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl RandomizedSet { - fn new() -> Self { RandomizedSet { - array: vec![0;200_001], + array: vec![0; 200_001], pos_table: HashMap::new(), pos_now: 0, - rng: rand::thread_rng() + rng: rand::thread_rng(), } } - + fn insert(&mut self, val: i32) -> bool { if self.pos_table.contains_key(&val) { return false; @@ -41,22 +38,22 @@ impl RandomizedSet { self.pos_now += 1; true } - + fn remove(&mut self, val: i32) -> bool { return match self.pos_table.get(&val) { Some(&pos) => { let last = self.array[self.pos_now - 1]; self.pos_table.insert(last, pos); self.array[pos] = last; - self.pos_now -= 1; + self.pos_now -= 1; self.pos_table.remove(&val); true - }, - None => false - } + } + None => false, + }; } - + fn get_random(&mut self) -> i32 { let pos = self.rng.gen_range(0..self.pos_now); self.array[pos] diff --git a/src/problem/p383_ransom_note.rs b/src/problem/p383_ransom_note.rs index dab850b..3e68c47 100644 --- a/src/problem/p383_ransom_note.rs +++ b/src/problem/p383_ransom_note.rs @@ -11,7 +11,7 @@ impl Solution { let mut map = HashMap::new(); for c in magazine.chars() { - let entry = map.entry(c).or_insert(0); + let entry = map.entry(c).or_insert(0); *entry += 1; } @@ -24,14 +24,13 @@ impl Solution { } *entry -= 1; - }, + } None => { return false; } } } - true } } diff --git a/src/problem/p392_is_subsequence.rs b/src/problem/p392_is_subsequence.rs index c936a35..2a43be5 100644 --- a/src/problem/p392_is_subsequence.rs +++ b/src/problem/p392_is_subsequence.rs @@ -3,12 +3,11 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn is_subsequence(s: String, t: String) -> bool { - let t : Vec = t.chars().collect(); + let t: Vec = t.chars().collect(); let mut pos = 0; for c in s.chars() { @@ -35,6 +34,9 @@ mod tests { #[test] fn test_392() { - assert!(Solution::is_subsequence("abc".to_owned(), "ahbgdc".to_owned())); + assert!(Solution::is_subsequence( + "abc".to_owned(), + "ahbgdc".to_owned() + )); } } diff --git a/src/problem/p399_evaluate_division.rs b/src/problem/p399_evaluate_division.rs index b6f1a40..10569e2 100644 --- a/src/problem/p399_evaluate_division.rs +++ b/src/problem/p399_evaluate_division.rs @@ -3,13 +3,12 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; struct UnionFind { - parents : Vec, - weights : Vec + parents: Vec, + weights: Vec, } impl UnionFind { @@ -22,10 +21,7 @@ impl UnionFind { weights.push(1f64); } - UnionFind { - parents, - weights - } + UnionFind { parents, weights } } fn find(&mut self, x: usize) -> usize { @@ -62,7 +58,11 @@ impl UnionFind { } impl Solution { - pub fn calc_equation(equations: Vec>, values: Vec, queries: Vec>) -> Vec { + pub fn calc_equation( + equations: Vec>, + values: Vec, + queries: Vec>, + ) -> Vec { let count = equations.len(); let mut union_find = UnionFind::new(count * 2); let mut id_map = HashMap::with_capacity(count * 2); @@ -70,7 +70,7 @@ impl Solution { for (i, equation) in equations.iter().enumerate() { let (x, y) = (&equation[0], &equation[1]); - + let x_id = *id_map.entry(x).or_insert_with(|| { let inserted_id = id; id += 1; @@ -95,10 +95,10 @@ impl Solution { if x_id.is_none() || y_id.is_none() { result.push(-1f64); } else { - result.push(union_find.is_connected(*x_id.unwrap(),*y_id.unwrap())); + result.push(union_find.is_connected(*x_id.unwrap(), *y_id.unwrap())); } } - + result } } diff --git a/src/problem/p39_combination_sum.rs b/src/problem/p39_combination_sum.rs index 30282c7..d138b31 100644 --- a/src/problem/p39_combination_sum.rs +++ b/src/problem/p39_combination_sum.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashSet; @@ -19,7 +18,13 @@ impl Solution { result.iter().map(|x| x.clone()).collect() } - fn dfs(candidates: &Vec, target: i32, path: &mut Vec, sum: i32, result: &mut HashSet>) { + fn dfs( + candidates: &Vec, + target: i32, + path: &mut Vec, + sum: i32, + result: &mut HashSet>, + ) { if sum > target { return; } @@ -52,10 +57,10 @@ mod tests { #[test] fn test_39() { let mut set = HashSet::new(); - - set.insert(vec![1,2]); - set.insert(vec![1,2]); - + + set.insert(vec![1, 2]); + set.insert(vec![1, 2]); + assert_eq!(set.len(), 1); } } diff --git a/src/problem/p3_longest_substring_without_repeating_characters.rs b/src/problem/p3_longest_substring_without_repeating_characters.rs index 41ebc6d..f3a822b 100644 --- a/src/problem/p3_longest_substring_without_repeating_characters.rs +++ b/src/problem/p3_longest_substring_without_repeating_characters.rs @@ -4,30 +4,30 @@ * Given a string s, find the length of the longest substring without repeating characters. * * Example 1: - * + * * Input: s = "abcabcbb" * Output: 3 * Explanation: The answer is "abc", with the length of 3. - * + * * Example 2: - * + * * Input: s = "bbbbb" * Output: 1 * Explanation: The answer is "b", with the length of 1. - * + * * Example 3: - * + * * Input: s = "pwwkew" * Output: 3 * Explanation: The answer is "wke", with the length of 3. * Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. - * + * * * Constraints: - * + * * 0 <= s.length <= 5 * 10^4 * s consists of English letters, digits, symbols and spaces. - * + * */ pub struct Solution {} @@ -67,8 +67,17 @@ mod tests { #[test] fn test_3() { - assert_eq!(3, Solution::length_of_longest_substring(String::from("abcabcbb"))); - assert_eq!(1, Solution::length_of_longest_substring(String::from("bbbbb"))); - assert_eq!(3, Solution::length_of_longest_substring(String::from("pwwkew"))); + assert_eq!( + 3, + Solution::length_of_longest_substring(String::from("abcabcbb")) + ); + assert_eq!( + 1, + Solution::length_of_longest_substring(String::from("bbbbb")) + ); + assert_eq!( + 3, + Solution::length_of_longest_substring(String::from("pwwkew")) + ); } } diff --git a/src/problem/p410_split_array_largest_sum.rs b/src/problem/p410_split_array_largest_sum.rs index 17f594c..e1f0b6b 100644 --- a/src/problem/p410_split_array_largest_sum.rs +++ b/src/problem/p410_split_array_largest_sum.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -60,8 +59,8 @@ mod tests { #[test] fn test_410() { - assert_eq!(Solution::split_array(vec![7,2,5,10,8], 2), 18); - assert_eq!(Solution::split_array(vec![1,2,3,4,5], 2), 9); - assert_eq!(Solution::split_array(vec![1,4,4], 3), 4); + assert_eq!(Solution::split_array(vec![7, 2, 5, 10, 8], 2), 18); + assert_eq!(Solution::split_array(vec![1, 2, 3, 4, 5], 2), 9); + assert_eq!(Solution::split_array(vec![1, 4, 4], 3), 4); } } diff --git a/src/problem/p447_number_of_boomerangs.rs b/src/problem/p447_number_of_boomerangs.rs index 8d46d56..104425d 100644 --- a/src/problem/p447_number_of_boomerangs.rs +++ b/src/problem/p447_number_of_boomerangs.rs @@ -5,30 +5,30 @@ * Return the number of boomerangs. * * Example 1: - * + * * Input: points = [[0,0],[1,0],[2,0]] * Output: 2 * Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]. - * + * * Example 2: - * + * * Input: points = [[1,1],[2,2],[3,3]] * Output: 2 - * + * * Example 3: - * + * * Input: points = [[1,1]] * Output: 0 - * + * * * Constraints: - * + * * n == points.length * 1 <= n <= 500 * points[i].length == 2 * -10^4 <= xi, yi <= 10^4 * All the points are unique. - * + * */ pub struct Solution {} @@ -55,7 +55,7 @@ impl Solution { for (_, v) in &values { // 实际上并不需要,因为最小值为1 // 计算的结果为0 - if *v >= 2 { + if *v >= 2 { // result += A_m^2 result += (*v) * (*v - 1); } @@ -73,6 +73,5 @@ mod tests { use super::*; #[test] - fn test_447() { - } + fn test_447() {} } diff --git a/src/problem/p452_minimum_number_of_arrows_to_burst_balloons.rs b/src/problem/p452_minimum_number_of_arrows_to_burst_balloons.rs index edf4460..9cc3eea 100644 --- a/src/problem/p452_minimum_number_of_arrows_to_burst_balloons.rs +++ b/src/problem/p452_minimum_number_of_arrows_to_burst_balloons.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -12,11 +11,9 @@ impl Solution { return 0; } - let mut points : Vec<(i32, i32)> = points.iter().map(|p|{(p[0], p[1])}).collect(); + let mut points: Vec<(i32, i32)> = points.iter().map(|p| (p[0], p[1])).collect(); - points.sort_unstable_by(|a, b| { - a.1.cmp(&b.1) - }); + points.sort_unstable_by(|a, b| a.1.cmp(&b.1)); let mut result = 0; let mut pos = points[0].1; @@ -39,6 +36,5 @@ mod tests { use super::*; #[test] - fn test_452() { - } + fn test_452() {} } diff --git a/src/problem/p46_permutations.rs b/src/problem/p46_permutations.rs index 98716fd..417faac 100644 --- a/src/problem/p46_permutations.rs +++ b/src/problem/p46_permutations.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -21,15 +20,14 @@ impl Solution { result.push(output.clone()); return; } - + for i in pos..length { Self::swap(output, i, pos); Self::search(length, output, result, pos + 1); Self::swap(output, i, pos); } - } - + fn swap(output: &mut Vec, a: usize, b: usize) { let temp = output[a]; output[a] = output[b]; @@ -44,6 +42,5 @@ mod tests { use super::*; #[test] - fn test_46() { - } + fn test_46() {} } diff --git a/src/problem/p48_rotate_image.rs b/src/problem/p48_rotate_image.rs index a68ecd6..c8be843 100644 --- a/src/problem/p48_rotate_image.rs +++ b/src/problem/p48_rotate_image.rs @@ -3,13 +3,12 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn rotate(matrix: &mut Vec>) { let n = matrix.len(); - + // 首先上下水平翻转 for i in (0..n / 2) { for j in 0..n { @@ -37,6 +36,5 @@ mod tests { use super::*; #[test] - fn test_48() { - } + fn test_48() {} } diff --git a/src/problem/p49_group_anagrams.rs b/src/problem/p49_group_anagrams.rs index 3f344c8..8877386 100644 --- a/src/problem/p49_group_anagrams.rs +++ b/src/problem/p49_group_anagrams.rs @@ -38,14 +38,13 @@ impl Eq for WordState {} impl Hash for WordState { fn hash(&self, state: &mut H) { - let mut chars: Vec<(&char, &usize)> = - self.characters.iter().map(|p| p).collect(); - + let mut chars: Vec<(&char, &usize)> = self.characters.iter().map(|p| p).collect(); + chars.sort_by_key(|p| p.0); for (&c, &v) in chars { c.hash(state); - v.hash(state); + v.hash(state); } } } diff --git a/src/problem/p4_median_of_two_sorted_arrays.rs b/src/problem/p4_median_of_two_sorted_arrays.rs index 1ab4d9f..37d066f 100644 --- a/src/problem/p4_median_of_two_sorted_arrays.rs +++ b/src/problem/p4_median_of_two_sorted_arrays.rs @@ -40,15 +40,23 @@ impl Solution { pub fn find_median_sorted_arrays(nums1: Vec, nums2: Vec) -> f64 { let len1 = nums1.len() as i32; let len2 = nums2.len() as i32; - let left = (len1 + len2 + 1) / 2 ; + let left = (len1 + len2 + 1) / 2; let right = (len1 + len2 + 2) / 2; - (Solution::get_k_th(&nums1, 0, len1 - 1, &nums2, 0, len2 - 1, left) as f64 + - Solution::get_k_th(&nums1, 0, len1 - 1, &nums2, 0, len2 - 1, right) as f64) * 0.5 + (Solution::get_k_th(&nums1, 0, len1 - 1, &nums2, 0, len2 - 1, left) as f64 + + Solution::get_k_th(&nums1, 0, len1 - 1, &nums2, 0, len2 - 1, right) as f64) + * 0.5 } - fn get_k_th(nums1: &Vec, start1: i32, end1: i32, - nums2: &Vec, start2: i32, end2: i32, k: i32) -> i32 { + fn get_k_th( + nums1: &Vec, + start1: i32, + end1: i32, + nums2: &Vec, + start2: i32, + end2: i32, + k: i32, + ) -> i32 { let len1 = end1 + 1 - start1; let len2 = end2 + 1 - start2; @@ -68,10 +76,26 @@ impl Solution { let j = start2 + min(len2, k / 2) - 1; return if nums1[i as usize] > nums2[j as usize] { - Solution::get_k_th(nums1, start1, end1, nums2, j + 1, end2, k - (j - start2 + 1)) + Solution::get_k_th( + nums1, + start1, + end1, + nums2, + j + 1, + end2, + k - (j - start2 + 1), + ) } else { - Solution::get_k_th(nums1, i + 1, end1, nums2, start2, end2, k - (i - start1 + 1)) - } + Solution::get_k_th( + nums1, + i + 1, + end1, + nums2, + start2, + end2, + k - (i - start1 + 1), + ) + }; } } @@ -83,8 +107,14 @@ mod tests { #[test] fn test_4() { - assert_eq!(2.0, Solution::find_median_sorted_arrays(vec![1, 3], vec![2])); - assert_eq!(2.5, Solution::find_median_sorted_arrays(vec![1, 2], vec![3, 4])); + assert_eq!( + 2.0, + Solution::find_median_sorted_arrays(vec![1, 3], vec![2]) + ); + assert_eq!( + 2.5, + Solution::find_median_sorted_arrays(vec![1, 2], vec![3, 4]) + ); assert_eq!(2.0, Solution::find_median_sorted_arrays(vec![2], vec![])); } } diff --git a/src/problem/p502_ipo.rs b/src/problem/p502_ipo.rs index 019c473..3374636 100644 --- a/src/problem/p502_ipo.rs +++ b/src/problem/p502_ipo.rs @@ -3,30 +3,29 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn find_maximized_capital(k: i32, w: i32, profits: Vec, capital: Vec) -> i32 { use std::collections::BinaryHeap; - + let mut array = vec![]; for (&p, &c) in profits.iter().zip(capital.iter()) { array.push((p, c)); } array.sort_by(|a, b| a.1.cmp(&b.1)); - + let mut result = w; let mut current = 0; let mut heap = BinaryHeap::new(); let n = array.len(); - + for _ in 0..k { while current < n && array[current].1 <= result { heap.push(array[current].0); current += 1; } - + if let Some(&head) = heap.peek() { result += head; heap.pop(); @@ -34,7 +33,7 @@ impl Solution { break; } } - + result } } @@ -46,6 +45,5 @@ mod tests { use super::*; #[test] - fn test_502() { - } + fn test_502() {} } diff --git a/src/problem/p50_powx_n.rs b/src/problem/p50_powx_n.rs index 9140dd0..1fc88c7 100644 --- a/src/problem/p50_powx_n.rs +++ b/src/problem/p50_powx_n.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -14,15 +13,15 @@ impl Solution { Self::quick_pow(x, n) } } - + fn quick_pow(x: f64, n: i32) -> f64 { if n == 0 { 1f64 - } else { + } else { let y = Self::quick_pow(x, n / 2); if n % 2 == 0 { y * y - } else { + } else { y * y * x } } @@ -36,6 +35,5 @@ mod tests { use super::*; #[test] - fn test_50() { - } + fn test_50() {} } diff --git a/src/problem/p514_freedom_trail.rs b/src/problem/p514_freedom_trail.rs index 3732ce2..cd58a93 100644 --- a/src/problem/p514_freedom_trail.rs +++ b/src/problem/p514_freedom_trail.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -19,7 +18,7 @@ impl Solution { let mut dp = Vec::with_capacity(key.len()); for _ in 0..key.len() { - dp.push(vec![i32::MAX;ring.len()]); + dp.push(vec![i32::MAX; ring.len()]); } let key: Vec = key.chars().collect(); @@ -40,8 +39,11 @@ impl Solution { let last = *j as i32; dp[index][*i] = dp[index][*i].min( - dp[index - 1][*j] + (now - last).abs().min( - ring.len() as i32 - (now - last).abs()) + 1 + dp[index - 1][*j] + + (now - last) + .abs() + .min(ring.len() as i32 - (now - last).abs()) + + 1, ) } } @@ -60,7 +62,13 @@ mod tests { #[test] fn test_514() { - assert_eq!(Solution::find_rotate_steps("godding".to_string(), "gd".to_string()), 4); - assert_eq!(Solution::find_rotate_steps("godding".to_string(), "godding".to_string()), 13); + assert_eq!( + Solution::find_rotate_steps("godding".to_string(), "gd".to_string()), + 4 + ); + assert_eq!( + Solution::find_rotate_steps("godding".to_string(), "godding".to_string()), + 13 + ); } } diff --git a/src/problem/p52_n_queens_ii.rs b/src/problem/p52_n_queens_ii.rs index 45ea770..690aa52 100644 --- a/src/problem/p52_n_queens_ii.rs +++ b/src/problem/p52_n_queens_ii.rs @@ -9,17 +9,17 @@ * Input: n = 4 * Output: 2 * Explanation: There are two distinct solutions to the 4-queens puzzle as shown. - * + * * Example 2: - * + * * Input: n = 1 * Output: 1 - * + * * * Constraints: - * + * * 1 <= n <= 9 - * + * */ pub struct Solution {} @@ -47,11 +47,11 @@ impl Solution { while let Some((x, y, flag)) = stack.pop_back() { if flag { x_occupied[y] = false; - y_occupied[n - 1 + x - y] = false; + y_occupied[n - 1 + x - y] = false; z_occupied[x + y] = false; } else { x_occupied[y] = true; - y_occupied[n - 1 + x - y] = true; + y_occupied[n - 1 + x - y] = true; z_occupied[x + y] = true; stack.push_back((x, y, true)); diff --git a/src/problem/p530_minimum_absolute_difference_in_bst.rs b/src/problem/p530_minimum_absolute_difference_in_bst.rs index 5c62f06..b897d6e 100644 --- a/src/problem/p530_minimum_absolute_difference_in_bst.rs +++ b/src/problem/p530_minimum_absolute_difference_in_bst.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,8 +25,8 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { fn inorder_iterate(node: &Rc>, arrap: &mut Vec) { if let Some(left) = node.borrow().left.as_ref() { @@ -46,7 +46,7 @@ impl Solution { if let Some(root) = root { Self::inorder_iterate(&root, &mut array); } - + let mut result = i32::MAX; for i in 1..array.len() { @@ -64,6 +64,5 @@ mod tests { use super::*; #[test] - fn test_530() { - } + fn test_530() {} } diff --git a/src/problem/p53_maximum_subarray.rs b/src/problem/p53_maximum_subarray.rs index b7879f1..4b7d6a8 100644 --- a/src/problem/p53_maximum_subarray.rs +++ b/src/problem/p53_maximum_subarray.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -27,6 +26,5 @@ mod tests { use super::*; #[test] - fn test_53() { - } + fn test_53() {} } diff --git a/src/problem/p551_student_attendance_record_i.rs b/src/problem/p551_student_attendance_record_i.rs index cad5eec..d55a12f 100644 --- a/src/problem/p551_student_attendance_record_i.rs +++ b/src/problem/p551_student_attendance_record_i.rs @@ -10,30 +10,30 @@ impl Solution { let s: Vec = s.chars().collect(); let mut late_count = 0; let mut absent_count = 0; - + for c in s { match c { 'A' => { absent_count += 1; late_count = 0; - + if absent_count >= 2 { return false; } - }, + } 'L' => { late_count += 1; - + if late_count >= 3 { return false; } - }, + } _ => { late_count = 0; } } } - + true } } diff --git a/src/problem/p552_student_attendance_record_ii.rs b/src/problem/p552_student_attendance_record_ii.rs index ce838cc..4c88b6e 100644 --- a/src/problem/p552_student_attendance_record_ii.rs +++ b/src/problem/p552_student_attendance_record_ii.rs @@ -3,17 +3,16 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn check_record(n: i32) -> i32 { let mod_number = 1_000_000_007; - let n =n as usize; - - let mut dp = vec![vec![vec![0;3];2];n + 1]; + let n = n as usize; + + let mut dp = vec![vec![vec![0; 3]; 2]; n + 1]; dp[0][0][0] = 1; - + for i in 1..=n { // record ends with 'P' for j in 0..2 { @@ -21,12 +20,12 @@ impl Solution { dp[i][j][0] = (dp[i][j][0] + dp[i - 1][j][k]) % mod_number; } } - + // record ends with 'A' for k in 0..3 { dp[i][1][0] = (dp[i][1][0] + dp[i - 1][0][k]) % mod_number; } - + // record ends with 'L' for j in 0..2 { for k in 1..3 { @@ -34,14 +33,14 @@ impl Solution { } } } - + let mut result = 0; for i in 0..2 { for j in 0..3 { - result = (result + dp[n][i][j]) % mod_number; + result = (result + dp[n][i][j]) % mod_number; } } - + result } } diff --git a/src/problem/p55_jump_game.rs b/src/problem/p55_jump_game.rs index e4f2f0e..7babe5e 100644 --- a/src/problem/p55_jump_game.rs +++ b/src/problem/p55_jump_game.rs @@ -19,7 +19,7 @@ impl Solution { if max_reach >= nums.len() - 1 { return true; } - } + } false } diff --git a/src/problem/p57_insert_interval.rs b/src/problem/p57_insert_interval.rs index 859ad40..da4e982 100644 --- a/src/problem/p57_insert_interval.rs +++ b/src/problem/p57_insert_interval.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -44,6 +43,5 @@ mod tests { use super::*; #[test] - fn test_57() { - } + fn test_57() {} } diff --git a/src/problem/p58_length_of_last_word.rs b/src/problem/p58_length_of_last_word.rs index e24a4fa..9c8320d 100644 --- a/src/problem/p58_length_of_last_word.rs +++ b/src/problem/p58_length_of_last_word.rs @@ -3,17 +3,16 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn length_of_last_word(s: String) -> i32 { - let words : Vec<&str> = s.split(' ').collect(); + let words: Vec<&str> = s.split(' ').collect(); for word in words.iter().rev() { if word.len() != 0 { return word.len() as i32; - } + } } 0 @@ -29,7 +28,13 @@ mod tests { #[test] fn test_58() { assert_eq!(5, Solution::length_of_last_word("Hello World".to_owned())); - assert_eq!(4, Solution::length_of_last_word(" fly me to the moon ".to_owned())); - assert_eq!(6, Solution::length_of_last_word("luffy is still joyboy".to_owned())); + assert_eq!( + 4, + Solution::length_of_last_word(" fly me to the moon ".to_owned()) + ); + assert_eq!( + 6, + Solution::length_of_last_word("luffy is still joyboy".to_owned()) + ); } } diff --git a/src/problem/p637_average_of_levels_in_binary_tree.rs b/src/problem/p637_average_of_levels_in_binary_tree.rs index caa8506..151bb52 100644 --- a/src/problem/p637_average_of_levels_in_binary_tree.rs +++ b/src/problem/p637_average_of_levels_in_binary_tree.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,9 +25,9 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; use std::collections::VecDeque; +use std::rc::Rc; impl Solution { pub fn average_of_levels(root: Option>>) -> Vec { let mut result = vec![]; @@ -70,6 +70,5 @@ mod tests { use super::*; #[test] - fn test_637() { - } + fn test_637() {} } diff --git a/src/problem/p63_unique_paths_ii.rs b/src/problem/p63_unique_paths_ii.rs index 127b9ff..2536013 100644 --- a/src/problem/p63_unique_paths_ii.rs +++ b/src/problem/p63_unique_paths_ii.rs @@ -3,18 +3,13 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn unique_paths_with_obstacles(obstacle_grid: Vec>) -> i32 { let (m, n) = (obstacle_grid.len(), obstacle_grid[0].len()); let mut dp = vec![vec![0; n]; m]; - dp[0][0] = if obstacle_grid[0][0] == 1 { - 0 - } else { - 1 - }; + dp[0][0] = if obstacle_grid[0][0] == 1 { 0 } else { 1 }; for i in 0..m { for j in 0..n { @@ -49,7 +44,14 @@ mod tests { #[test] fn test_63() { - assert_eq!(2, Solution::unique_paths_with_obstacles(vec![vec![0, 0, 0], vec![0, 1, 0], vec![0, 0, 0]])); + assert_eq!( + 2, + Solution::unique_paths_with_obstacles(vec![ + vec![0, 0, 0], + vec![0, 1, 0], + vec![0, 0, 0] + ]) + ); assert_eq!(0, Solution::unique_paths_with_obstacles(vec![vec![1]])); } } diff --git a/src/problem/p64_minimum_path_sum.rs b/src/problem/p64_minimum_path_sum.rs index fd10750..f647ac5 100644 --- a/src/problem/p64_minimum_path_sum.rs +++ b/src/problem/p64_minimum_path_sum.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -41,6 +40,9 @@ mod tests { #[test] fn test_64() { - assert_eq!(7, Solution::min_path_sum(vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]])); + assert_eq!( + 7, + Solution::min_path_sum(vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]]) + ); } } diff --git a/src/problem/p66_plus_one.rs b/src/problem/p66_plus_one.rs index fb57d53..7ae9003 100644 --- a/src/problem/p66_plus_one.rs +++ b/src/problem/p66_plus_one.rs @@ -3,20 +3,19 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn plus_one(digits: Vec) -> Vec { let mut digits = digits; let mut overflow = 1; - + for i in (0..digits.len()).rev() { let bit = digits[i] + overflow; digits[i] = bit % 10; overflow = bit / 10; } - + if overflow > 0 { digits.insert(0, overflow); } diff --git a/src/problem/p670_maximum_swap.rs b/src/problem/p670_maximum_swap.rs index 7193013..abdec5f 100644 --- a/src/problem/p670_maximum_swap.rs +++ b/src/problem/p670_maximum_swap.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p67_add_binary.rs b/src/problem/p67_add_binary.rs index a2901c8..2d0e343 100644 --- a/src/problem/p67_add_binary.rs +++ b/src/problem/p67_add_binary.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -16,27 +15,39 @@ impl Solution { let mut overflow = 0; for i in 0..a.len().max(b.len()) { let mut bit = overflow; - + if i < a.len() { bit += a[i]; } if i < b.len() { bit += b[i]; } - - match bit { - 3 => {result.push(1); overflow = 1}, - 2 => {result.push(0); overflow = 1}, - 1 => {result.push(1); overflow = 0}, - 0 => {result.push(0); overflow = 0}, + + match bit { + 3 => { + result.push(1); + overflow = 1 + } + 2 => { + result.push(0); + overflow = 1 + } + 1 => { + result.push(1); + overflow = 0 + } + 0 => { + result.push(0); + overflow = 0 + } _ => {} } } - + if overflow != 0 { result.push(overflow); } - + if result.len() == 0 { result.push(0); } @@ -53,8 +64,17 @@ mod tests { #[test] fn test_67() { - assert_eq!("100".to_owned(), Solution::add_binary("11".to_owned(), "1".to_owned())); - assert_eq!("10101".to_owned(), Solution::add_binary("1010".to_owned(), "1011".to_owned())); - assert_eq!("110110".to_owned(), Solution::add_binary("100".to_owned(), "110010".to_owned())); + assert_eq!( + "100".to_owned(), + Solution::add_binary("11".to_owned(), "1".to_owned()) + ); + assert_eq!( + "10101".to_owned(), + Solution::add_binary("1010".to_owned(), "1011".to_owned()) + ); + assert_eq!( + "110110".to_owned(), + Solution::add_binary("100".to_owned(), "110010".to_owned()) + ); } } diff --git a/src/problem/p68_text_justification.rs b/src/problem/p68_text_justification.rs index f1fca38..f82aefd 100644 --- a/src/problem/p68_text_justification.rs +++ b/src/problem/p68_text_justification.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -13,7 +12,7 @@ impl Solution { let mut result = Vec::with_capacity(words.len()); let mut line_length = 0; - let mut lines : Vec = Vec::new(); + let mut lines: Vec = Vec::new(); while pos < words.len() { if line_length + words[pos].len() > max_width { let line_count = lines.len(); @@ -33,7 +32,7 @@ impl Solution { let actual_line_length: usize = lines.iter().map(|word| word.len()).sum(); let mut mod_length = (max_width - actual_line_length) % (line_count - 1); - let average_length = (max_width - actual_line_length) / (line_count - 1); + let average_length = (max_width - actual_line_length) / (line_count - 1); for i in 0..line_count { line.push_str(&lines[i]); @@ -48,8 +47,8 @@ impl Solution { for j in 0..space_length { line.push(' '); - } - } + } + } } result.push(line); @@ -92,8 +91,16 @@ mod tests { #[test] fn test_68() { - let words = vec!["This", "is", "an", "example", "of", "text", "justification."]; - let words: Vec = words.iter().map(|word| {String::from(*word)}).collect(); + let words = vec![ + "This", + "is", + "an", + "example", + "of", + "text", + "justification.", + ]; + let words: Vec = words.iter().map(|word| String::from(*word)).collect(); for line in Solution::full_justify(words, 16) { println!("{}", line); diff --git a/src/problem/p698_partition_to_k_equal_sum_subsets.rs b/src/problem/p698_partition_to_k_equal_sum_subsets.rs index 4077520..1601926 100644 --- a/src/problem/p698_partition_to_k_equal_sum_subsets.rs +++ b/src/problem/p698_partition_to_k_equal_sum_subsets.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -40,7 +39,9 @@ impl Solution { break; } - if (state >> i) & 1 == 1 && Self::search(state ^ (1 << i), (now + n) % target, dp, target, nums) { + if (state >> i) & 1 == 1 + && Self::search(state ^ (1 << i), (now + n) % target, dp, target, nums) + { return true; } } @@ -57,6 +58,9 @@ mod tests { #[test] fn test_698() { - assert!(Solution::can_partition_k_subsets(vec![4, 3, 2, 3, 5, 2, 1], 4)); + assert!(Solution::can_partition_k_subsets( + vec![4, 3, 2, 3, 5, 2, 1], + 4 + )); } } diff --git a/src/problem/p69_sqrtx.rs b/src/problem/p69_sqrtx.rs index 09b6630..d46479c 100644 --- a/src/problem/p69_sqrtx.rs +++ b/src/problem/p69_sqrtx.rs @@ -1,10 +1,8 @@ - /** * [69] Sqrt(x) */ pub struct Solution {} - // submission codes start here impl Solution { @@ -13,7 +11,7 @@ impl Solution { if x == 0 { return 0; } - + let c = x as f64; let mut x = x as f64; @@ -24,7 +22,7 @@ impl Solution { } x = xi; } - + return x as i32; } } diff --git a/src/problem/p6_zigzag_conversion.rs b/src/problem/p6_zigzag_conversion.rs index 510085d..27e8d95 100644 --- a/src/problem/p6_zigzag_conversion.rs +++ b/src/problem/p6_zigzag_conversion.rs @@ -2,24 +2,24 @@ * [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: @@ -27,19 +27,19 @@ * A L S I G * Y A H R * P I - * + * * Example 3: - * + * * Input: s = "A", numRows = 1 * Output: "A" - * + * * * Constraints: - * + * * 1 <= s.length <= 1000 * s consists of English letters (lower-case and upper-case), ',' and '.'. * 1 <= numRows <= 1000 - * + * */ pub struct Solution {} @@ -91,8 +91,9 @@ mod tests { #[test] fn test_6() { - assert_eq!(String::from("PAHNAPLSIIGYIR"), Solution::convert( - String::from("PAYPALISHIRING"), 3 - )); + assert_eq!( + String::from("PAHNAPLSIIGYIR"), + Solution::convert(String::from("PAYPALISHIRING"), 3) + ); } } diff --git a/src/problem/p70_climbing_stairs.rs b/src/problem/p70_climbing_stairs.rs index 8ce2da2..1f79a6a 100644 --- a/src/problem/p70_climbing_stairs.rs +++ b/src/problem/p70_climbing_stairs.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -13,16 +12,16 @@ impl Solution { } else if n == 2 { return 2; } - + let mut last_last = 1; let mut last = 2; - + for i in 3..=n { let now = last + last_last; last_last = last; last = now; } - + last } } diff --git a/src/problem/p71_simplify_path.rs b/src/problem/p71_simplify_path.rs index 9c06c34..6e41527 100644 --- a/src/problem/p71_simplify_path.rs +++ b/src/problem/p71_simplify_path.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -22,7 +21,7 @@ impl Solution { path.pop(); } else { path.push(name) - } + } } let mut result = String::new(); @@ -30,7 +29,7 @@ impl Solution { for name in path { result.push_str("/"); result.push_str(name); - } + } if result.len() == 0 { "/".to_owned() @@ -48,6 +47,9 @@ mod tests { #[test] fn test_71() { - assert_eq!("/home".to_owned(), Solution::simplify_path("/home//".to_owned())); + assert_eq!( + "/home".to_owned(), + Solution::simplify_path("/home//".to_owned()) + ); } } diff --git a/src/problem/p72_edit_distance.rs b/src/problem/p72_edit_distance.rs index 49ccf51..cc9cdc3 100644 --- a/src/problem/p72_edit_distance.rs +++ b/src/problem/p72_edit_distance.rs @@ -3,43 +3,43 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn min_distance(word1: String, word2: String) -> i32 { - let (word1, word2): (Vec, Vec) = (word1.chars().collect(), word2.chars().collect()); + let (word1, word2): (Vec, Vec) = + (word1.chars().collect(), word2.chars().collect()); let (n, m) = (word1.len(), word2.len()); - + // 存在一个字符串有空串 if m * n == 0 { return (m + n) as i32; } - - let mut dp = vec![vec![0;m + 1]; n + 1]; - + + let mut dp = vec![vec![0; m + 1]; n + 1]; + // 初始化dp数组 for i in 0..=n { dp[i][0] = i; } - + for i in 0..=m { dp[0][i] = i; } - + for i in 1..=n { for j in 1..=m { let left = dp[i - 1][j] + 1; let down = dp[i][j - 1] + 1; - let mut left_down = dp[i - 1][ j -1]; + let mut left_down = dp[i - 1][j - 1]; if word1[i - 1] != word2[j - 1] { left_down += 1; } - + dp[i][j] = left.min(down).min(left_down); } } - + dp[n][m] as i32 } } @@ -52,6 +52,9 @@ mod tests { #[test] fn test_72() { - assert_eq!(3, Solution::min_distance("horse".to_owned(), "ros".to_owned())); + assert_eq!( + 3, + Solution::min_distance("horse".to_owned(), "ros".to_owned()) + ); } } diff --git a/src/problem/p743_network_delay_time.rs b/src/problem/p743_network_delay_time.rs index 910144f..9773336 100644 --- a/src/problem/p743_network_delay_time.rs +++ b/src/problem/p743_network_delay_time.rs @@ -8,20 +8,20 @@ * * Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2 * Output: 2 - * + * * Example 2: - * + * * Input: times = [[1,2,1]], n = 2, k = 1 * Output: 1 - * + * * Example 3: - * + * * Input: times = [[1,2,1]], n = 2, k = 2 * Output: -1 - * + * * * Constraints: - * + * * 1 <= k <= n <= 100 * 1 <= times.length <= 6000 * times[i].length == 3 @@ -29,7 +29,7 @@ * ui != vi * 0 <= wi <= 100 * All the pairs (ui, vi) are unique. (i.e., no multiple edges.) - * + * */ pub struct Solution {} @@ -99,17 +99,13 @@ impl Solution { for i in 1..distances.len() { if i == k { - continue + continue; } result = max(result, distances[i]); } - return if result == i32::MAX { - -1 - } else { - result - } + return if result == i32::MAX { -1 } else { result }; } } @@ -121,9 +117,11 @@ mod tests { #[test] fn test_743() { - assert_eq!(Solution::network_delay_time( - vec![vec![2,1,1], vec![2,3,1], vec![3,4,1]], 4, 2), 2); - assert_eq!(Solution::network_delay_time(vec![vec![1,2,1]], 2, 1), 1); - assert_eq!(Solution::network_delay_time(vec![vec![1,2,1]], 2, 2), -1); + assert_eq!( + Solution::network_delay_time(vec![vec![2, 1, 1], vec![2, 3, 1], vec![3, 4, 1]], 4, 2), + 2 + ); + assert_eq!(Solution::network_delay_time(vec![vec![1, 2, 1]], 2, 1), 1); + assert_eq!(Solution::network_delay_time(vec![vec![1, 2, 1]], 2, 2), -1); } } diff --git a/src/problem/p74_search_a_2d_matrix.rs b/src/problem/p74_search_a_2d_matrix.rs index 7c816fb..8b16f86 100644 --- a/src/problem/p74_search_a_2d_matrix.rs +++ b/src/problem/p74_search_a_2d_matrix.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -16,7 +15,7 @@ impl Solution { while lower < upper { let middle = (upper - lower) / 2 + lower; - + // WTF? if lower == middle { break; @@ -43,7 +42,7 @@ impl Solution { if left < n { matrix[lower][left] == target - } else { + } else { false } } @@ -58,11 +57,11 @@ mod tests { #[test] fn test_74() { let matrix = vec![vec![1, 3, 5, 7], vec![10, 11, 16, 20], vec![23, 30, 34, 60]]; - + assert!(Solution::search_matrix(matrix, 3)); - + let matrix = vec![vec![1]]; - + assert!(!Solution::search_matrix(matrix, 2)); } } diff --git a/src/problem/p76_minimum_window_substring.rs b/src/problem/p76_minimum_window_substring.rs index 0b78eda..33da114 100644 --- a/src/problem/p76_minimum_window_substring.rs +++ b/src/problem/p76_minimum_window_substring.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashMap; @@ -16,10 +15,10 @@ impl Solution { *entry += 1; } - let s : Vec = s.chars().collect(); + let s: Vec = s.chars().collect(); let mut s_map = HashMap::new(); - let (mut i , mut j) = (0, 0); + let (mut i, mut j) = (0, 0); let mut result_left = 0; let mut result_length = usize::MAX; @@ -51,7 +50,7 @@ impl Solution { } } - fn check_map(s : &HashMap, t : &HashMap) -> bool { + fn check_map(s: &HashMap, t: &HashMap) -> bool { for (key, value) in t { match s.get(key) { Some(real_value) => { @@ -77,6 +76,9 @@ mod tests { #[test] fn test_76() { - assert_eq!("BANC".to_owned(), Solution::min_window("ADOBECODEBANC".to_owned(), "ABC".to_owned())); + assert_eq!( + "BANC".to_owned(), + Solution::min_window("ADOBECODEBANC".to_owned(), "ABC".to_owned()) + ); } } diff --git a/src/problem/p77_combinations.rs b/src/problem/p77_combinations.rs index 225ca5c..6db927c 100644 --- a/src/problem/p77_combinations.rs +++ b/src/problem/p77_combinations.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -40,6 +39,5 @@ mod tests { use super::*; #[test] - fn test_77() { - } + fn test_77() {} } diff --git a/src/problem/p79_word_search.rs b/src/problem/p79_word_search.rs index 40055b9..f615070 100644 --- a/src/problem/p79_word_search.rs +++ b/src/problem/p79_word_search.rs @@ -3,16 +3,15 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn exist(board: Vec>, word: String) -> bool { let word: Vec = word.chars().collect(); - + let (m, n) = (board.len(), board[0].len()); - let mut visited = vec![vec![false;n];m]; + let mut visited = vec![vec![false; n]; m]; for i in 0..m { for j in 0..n { if board[i][j] == word[0] { @@ -26,7 +25,14 @@ impl Solution { false } - fn search(board: &Vec>, word: &Vec, visited: &mut Vec>, x: i32, y: i32, pos: usize) -> bool { + fn search( + board: &Vec>, + word: &Vec, + visited: &mut Vec>, + x: i32, + y: i32, + pos: usize, + ) -> bool { if pos == word.len() { return true; } @@ -36,9 +42,9 @@ impl Solution { if x < 0 || x >= m || y < 0 || y >= n { return false; } - + let (x_pos, y_pos) = (x as usize, y as usize); - + if visited[x_pos][y_pos] { return false; } diff --git a/src/problem/p7_reverse_integer.rs b/src/problem/p7_reverse_integer.rs index 13d9b6f..9fb5213 100644 --- a/src/problem/p7_reverse_integer.rs +++ b/src/problem/p7_reverse_integer.rs @@ -5,25 +5,25 @@ * Assume the environment does not allow you to store 64-bit integers (signed or unsigned). * * Example 1: - * + * * Input: x = 123 * Output: 321 - * + * * Example 2: - * + * * Input: x = -123 * Output: -321 - * + * * Example 3: - * + * * Input: x = 120 * Output: 21 - * + * * * Constraints: - * + * * -2^31 <= x <= 2^31 - 1 - * + * */ pub struct Solution {} @@ -34,11 +34,7 @@ pub struct Solution {} impl Solution { pub fn reverse(x: i32) -> i32 { - let (num, negative) = if x < 0 { - (-x, true) - } else { - (x, false) - }; + let (num, negative) = if x < 0 { (-x, true) } else { (x, false) }; let str = num.to_string(); let mut str: String = str.chars().rev().collect(); diff --git a/src/problem/p80_remove_duplicates_from_sorted_array_ii.rs b/src/problem/p80_remove_duplicates_from_sorted_array_ii.rs index c34a85a..df96c5b 100644 --- a/src/problem/p80_remove_duplicates_from_sorted_array_ii.rs +++ b/src/problem/p80_remove_duplicates_from_sorted_array_ii.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -25,7 +24,7 @@ impl Solution { count += 1; } } - + now as i32 } } @@ -38,8 +37,8 @@ mod tests { #[test] fn test_80() { - let mut nums = vec![1,1,1,2,2,3]; + let mut nums = vec![1, 1, 1, 2, 2, 3]; assert_eq!(5, Solution::remove_duplicates(&mut nums)); - assert_eq!(vec![1,1,2,2,3,3], nums); + assert_eq!(vec![1, 1, 2, 2, 3, 3], nums); } } diff --git a/src/problem/p815_bus_routes.rs b/src/problem/p815_bus_routes.rs index 2638690..bea63a2 100644 --- a/src/problem/p815_bus_routes.rs +++ b/src/problem/p815_bus_routes.rs @@ -3,13 +3,12 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn num_buses_to_destination(routes: Vec>, source: i32, target: i32) -> i32 { - use std::collections::{VecDeque, HashMap}; - + use std::collections::{HashMap, VecDeque}; + if source == target { return 0; } @@ -36,13 +35,13 @@ impl Solution { let mut distances = vec![-1; n]; let mut queue = VecDeque::new(); - + if let Some(source_buses) = map.get(&source) { for &bus in source_buses { distances[bus] = 1; - queue.push_back(bus); + queue.push_back(bus); } - } else { + } else { // 没有任何公交车经过起始站点 return -1; } @@ -64,14 +63,14 @@ impl Solution { for &bus in target_buses { result = result.min(distances[bus]); } - } else { + } else { // 没有任何公交车经过终点站点 return -1; } if result == i32::MAX { -1 - } else { + } else { result } } @@ -85,6 +84,9 @@ mod tests { #[test] fn test_815() { - assert_eq!(2, Solution::num_buses_to_destination(vec![vec![1, 2, 7], vec![3, 6, 7]], 1, 6)); + assert_eq!( + 2, + Solution::num_buses_to_destination(vec![vec![1, 2, 7], vec![3, 6, 7]], 1, 6) + ); } } diff --git a/src/problem/p82_remove_duplicates_from_sorted_list_ii.rs b/src/problem/p82_remove_duplicates_from_sorted_list_ii.rs index 67045a0..755f4a0 100644 --- a/src/problem/p82_remove_duplicates_from_sorted_list_ii.rs +++ b/src/problem/p82_remove_duplicates_from_sorted_list_ii.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::linked_list::{ListNode, to_list}; +use crate::util::linked_list::{to_list, ListNode}; // submission codes start here @@ -38,8 +38,8 @@ impl Solution { let now = node.val; if head.as_ref().map_or(true, |next| next.val != now) - && prev.map_or(true, |pre| pre != now) { - + && prev.map_or(true, |pre| pre != now) + { tail.next = Some(node); tail = tail.next.as_mut()?; } @@ -58,6 +58,5 @@ mod tests { use super::*; #[test] - fn test_82() { - } + fn test_82() {} } diff --git a/src/problem/p83_remove_duplicates_from_sorted_list.rs b/src/problem/p83_remove_duplicates_from_sorted_list.rs index 723c7b5..759d69a 100644 --- a/src/problem/p83_remove_duplicates_from_sorted_list.rs +++ b/src/problem/p83_remove_duplicates_from_sorted_list.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::linked_list::{ListNode, to_list}; +use crate::util::linked_list::{to_list, ListNode}; // submission codes start here @@ -33,7 +33,7 @@ impl Solution { if node.val == next.val { node.next = next.next.take(); } else { - break + break; } } @@ -51,6 +51,5 @@ mod tests { use super::*; #[test] - fn test_83() { - } + fn test_83() {} } diff --git a/src/problem/p871_minimum_number_of_refueling_stops.rs b/src/problem/p871_minimum_number_of_refueling_stops.rs index d86b3c7..aa85037 100644 --- a/src/problem/p871_minimum_number_of_refueling_stops.rs +++ b/src/problem/p871_minimum_number_of_refueling_stops.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -50,6 +49,13 @@ mod tests { fn test_871() { assert_eq!(0, Solution::min_refuel_stops(1, 1, vec![])); assert_eq!(-1, Solution::min_refuel_stops(100, 1, vec![vec![10, 100]])); - assert_eq!(2, Solution::min_refuel_stops(100, 10, vec![vec![10, 60], vec![20, 30], vec![30, 30], vec![60, 40]])); + assert_eq!( + 2, + Solution::min_refuel_stops( + 100, + 10, + vec![vec![10, 60], vec![20, 30], vec![30, 30], vec![60, 40]] + ) + ); } } diff --git a/src/problem/p887_super_egg_drop.rs b/src/problem/p887_super_egg_drop.rs index c3af74e..03a7c59 100644 --- a/src/problem/p887_super_egg_drop.rs +++ b/src/problem/p887_super_egg_drop.rs @@ -46,7 +46,8 @@ impl Solution { } } - 1 + Self::dp(k - 1, left - 1, memory).max(Self::dp(k, n - left, memory)) + 1 + Self::dp(k - 1, left - 1, memory) + .max(Self::dp(k, n - left, memory)) .min(Self::dp(k - 1, right - 1, memory).max(Self::dp(k, n - right, memory))) }; diff --git a/src/problem/p889_construct_binary_tree_from_preorder_and_postorder_traversal.rs b/src/problem/p889_construct_binary_tree_from_preorder_and_postorder_traversal.rs index 0c660a9..356e9bb 100644 --- a/src/problem/p889_construct_binary_tree_from_preorder_and_postorder_traversal.rs +++ b/src/problem/p889_construct_binary_tree_from_preorder_and_postorder_traversal.rs @@ -9,7 +9,6 @@ use crate::util::tree::{to_tree, TreeNode}; // submission codes start here - // Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { diff --git a/src/problem/p88_merge_sorted_array.rs b/src/problem/p88_merge_sorted_array.rs index cf9533c..ba70b26 100644 --- a/src/problem/p88_merge_sorted_array.rs +++ b/src/problem/p88_merge_sorted_array.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -32,7 +31,6 @@ impl Solution { break; } - if nums1[i] < nums2[j] { result.push(nums1[i]); i += 1; @@ -44,7 +42,7 @@ impl Solution { for (index, &value) in result.iter().enumerate() { nums1[index] = value; - } + } } } diff --git a/src/problem/p908_smallest_range_i.rs b/src/problem/p908_smallest_range_i.rs index ad4f64b..74b9410 100644 --- a/src/problem/p908_smallest_range_i.rs +++ b/src/problem/p908_smallest_range_i.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p910_smallest_range_ii.rs b/src/problem/p910_smallest_range_ii.rs index de38376..b4dcac3 100644 --- a/src/problem/p910_smallest_range_ii.rs +++ b/src/problem/p910_smallest_range_ii.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p912_sort_an_array.rs b/src/problem/p912_sort_an_array.rs index 1b16325..a7d4aea 100644 --- a/src/problem/p912_sort_an_array.rs +++ b/src/problem/p912_sort_an_array.rs @@ -5,23 +5,23 @@ * You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible. * * Example 1: - * + * * Input: nums = [5,2,3,1] * Output: [1,2,3,5] * Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5). - * + * * Example 2: - * + * * Input: nums = [5,1,1,2,0,0] * Output: [0,0,1,1,2,5] * Explanation: Note that the values of nums are not necessairly unique. - * + * * * Constraints: - * + * * 1 <= nums.length <= 5 * 10^4 * -5 * 10^4 <= nums[i] <= 5 * 10^4 - * + * */ pub struct Solution {} @@ -90,6 +90,9 @@ mod tests { #[test] fn test_912() { assert_eq!(vec![1, 2, 3, 5], Solution::sort_array(vec![5, 2, 3, 1])); - assert_eq!(vec![0, 0, 1, 1, 2, 5], Solution::sort_array(vec![5, 1, 1, 2, 0, 0])); + assert_eq!( + vec![0, 0, 1, 1, 2, 5], + Solution::sort_array(vec![5, 1, 1, 2, 0, 0]) + ); } } diff --git a/src/problem/p918_maximum_sum_circular_subarray.rs b/src/problem/p918_maximum_sum_circular_subarray.rs index 5c4c988..65fd24f 100644 --- a/src/problem/p918_maximum_sum_circular_subarray.rs +++ b/src/problem/p918_maximum_sum_circular_subarray.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::VecDeque; @@ -41,6 +40,5 @@ mod tests { use super::*; #[test] - fn test_918() { - } + fn test_918() {} } diff --git a/src/problem/p938_range_sum_of_bst.rs b/src/problem/p938_range_sum_of_bst.rs index dd1b277..e7bcf09 100644 --- a/src/problem/p938_range_sum_of_bst.rs +++ b/src/problem/p938_range_sum_of_bst.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,9 +25,9 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; use std::collections::VecDeque; +use std::rc::Rc; impl Solution { pub fn range_sum_bst(root: Option>>, low: i32, high: i32) -> i32 { let root = if let Some(r) = root { @@ -73,7 +73,21 @@ mod tests { #[test] fn test_938() { - assert_eq!(Solution::range_sum_bst( - to_tree(vec![Some(10), Some(5), Some(15), Some(3), Some(7), None, Some(18)]), 7, 15), 32); + assert_eq!( + Solution::range_sum_bst( + to_tree(vec![ + Some(10), + Some(5), + Some(15), + Some(3), + Some(7), + None, + Some(18) + ]), + 7, + 15 + ), + 32 + ); } } diff --git a/src/problem/p94_binary_tree_inorder_traversal.rs b/src/problem/p94_binary_tree_inorder_traversal.rs index 23db866..8fd8f53 100644 --- a/src/problem/p94_binary_tree_inorder_traversal.rs +++ b/src/problem/p94_binary_tree_inorder_traversal.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,8 +25,8 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { pub fn inorder_traversal(root: Option>>) -> Vec { let mut result = Vec::new(); @@ -57,6 +57,5 @@ mod tests { use super::*; #[test] - fn test_94() { - } + fn test_94() {} } diff --git a/src/problem/p977_squares_of_a_sorted_array.rs b/src/problem/p977_squares_of_a_sorted_array.rs index c294356..372aced 100644 --- a/src/problem/p977_squares_of_a_sorted_array.rs +++ b/src/problem/p977_squares_of_a_sorted_array.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { @@ -47,8 +46,14 @@ mod tests { #[test] fn test_977() { - assert_eq!(vec![0, 1, 9, 16, 100], Solution::sorted_squares(vec![-4, -1, 0, 3, 10])); - assert_eq!(vec![4, 9, 9, 49, 121], Solution::sorted_squares(vec![-7, -3, 2, 3, 11])); + assert_eq!( + vec![0, 1, 9, 16, 100], + Solution::sorted_squares(vec![-4, -1, 0, 3, 10]) + ); + assert_eq!( + vec![4, 9, 9, 49, 121], + Solution::sorted_squares(vec![-7, -3, 2, 3, 11]) + ); assert_eq!(vec![1, 4], Solution::sorted_squares(vec![-2, -1])); } } diff --git a/src/problem/p97_interleaving_string.rs b/src/problem/p97_interleaving_string.rs index e7c5ad1..faad614 100644 --- a/src/problem/p97_interleaving_string.rs +++ b/src/problem/p97_interleaving_string.rs @@ -3,12 +3,15 @@ */ pub struct Solution {} - // submission codes start here impl Solution { pub fn is_interleave(s1: String, s2: String, s3: String) -> bool { - let (s1, s2, s3): (Vec, Vec, Vec) = (s1.chars().collect(), s2.chars().collect(), s3.chars().collect()); + let (s1, s2, s3): (Vec, Vec, Vec) = ( + s1.chars().collect(), + s2.chars().collect(), + s3.chars().collect(), + ); let (n, m, t) = (s1.len(), s2.len(), s3.len()); if n + m != t { @@ -48,6 +51,10 @@ mod tests { #[test] fn test_97() { - assert!(Solution::is_interleave("aabcc".to_owned(), "dbbca".to_owned(), "aadbbcbcac".to_owned())); + assert!(Solution::is_interleave( + "aabcc".to_owned(), + "dbbca".to_owned(), + "aadbbcbcac".to_owned() + )); } } diff --git a/src/problem/p983_minimum_cost_for_tickets.rs b/src/problem/p983_minimum_cost_for_tickets.rs index af75b5d..5e43a54 100644 --- a/src/problem/p983_minimum_cost_for_tickets.rs +++ b/src/problem/p983_minimum_cost_for_tickets.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here use std::collections::HashSet; @@ -11,27 +10,32 @@ impl Solution { pub fn mincost_tickets(days: Vec, costs: Vec) -> i32 { let mut memory = vec![None; 366]; let days: HashSet = days.iter().map(|x| *x as usize).collect(); - + Self::dp(1, &mut memory, &days, &costs) } - - fn dp(day: usize, memory: &mut Vec>, days: &HashSet, costs: &Vec) -> i32 { + + fn dp( + day: usize, + memory: &mut Vec>, + days: &HashSet, + costs: &Vec, + ) -> i32 { if day > 365 { return 0; } - + if let Some(result) = memory[day] { return result; } - + let result = if days.contains(&day) { (Self::dp(day + 1, memory, days, costs) + costs[0]) .min(Self::dp(day + 7, memory, days, costs) + costs[1]) .min(Self::dp(day + 30, memory, days, costs) + costs[2]) - } else { + } else { Self::dp(day + 1, memory, days, costs) }; - + memory[day] = Some(result); result } @@ -45,7 +49,13 @@ mod tests { #[test] fn test_983() { - assert_eq!(11, Solution::mincost_tickets(vec![1, 4, 6, 7, 8, 20], vec![2, 7, 15])); - assert_eq!(17, Solution::mincost_tickets(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], vec![2, 7, 15])); + assert_eq!( + 11, + Solution::mincost_tickets(vec![1, 4, 6, 7, 8, 20], vec![2, 7, 15]) + ); + assert_eq!( + 17, + Solution::mincost_tickets(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], vec![2, 7, 15]) + ); } } diff --git a/src/problem/p987_vertical_order_traversal_of_a_binary_tree.rs b/src/problem/p987_vertical_order_traversal_of_a_binary_tree.rs index 4204aeb..93e07ab 100644 --- a/src/problem/p987_vertical_order_traversal_of_a_binary_tree.rs +++ b/src/problem/p987_vertical_order_traversal_of_a_binary_tree.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,32 +25,30 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; #[derive(Debug)] struct Node { x: i32, y: i32, - val: i32 + val: i32, } struct DFS { - nodes: Vec + nodes: Vec, } impl DFS { fn new() -> DFS { - DFS { - nodes: Vec::new() - } + DFS { nodes: Vec::new() } } fn search(&mut self, node: &Rc>, x: i32, y: i32) { self.nodes.push(Node { val: node.borrow().val, x, - y + y, }); if let Some(left) = &node.borrow().left { @@ -77,13 +75,13 @@ impl Solution { dfs.search(&root, 0, 0); dfs.nodes.sort_unstable_by(|a, b| { - if a.x != b.x { - a.x.cmp(&b.x) - } else if a.y != b.y { - a.y.cmp(&b.y) - } else { - a.val.cmp(&b.val) - } + if a.x != b.x { + a.x.cmp(&b.x) + } else if a.y != b.y { + a.y.cmp(&b.y) + } else { + a.val.cmp(&b.val) + } }); let mut last = None; @@ -114,8 +112,17 @@ mod tests { #[test] fn test_987() { - assert_eq!(Solution::vertical_traversal( - to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)]) - ), vec![vec![9], vec![3, 15], vec![20], vec![7]]); + assert_eq!( + Solution::vertical_traversal(to_tree(vec![ + Some(3), + Some(9), + Some(20), + None, + None, + Some(15), + Some(7) + ])), + vec![vec![9], vec![3, 15], vec![20], vec![7]] + ); } } diff --git a/src/problem/p98_validate_binary_search_tree.rs b/src/problem/p98_validate_binary_search_tree.rs index e86b398..722abb3 100644 --- a/src/problem/p98_validate_binary_search_tree.rs +++ b/src/problem/p98_validate_binary_search_tree.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,13 +25,13 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; impl Solution { fn inorder_iterate(node: &Rc>, array: &mut Vec) { if let Some(left) = node.borrow().left.as_ref() { Self::inorder_iterate(left, array); - } + } array.push(node.borrow().val); if let Some(right) = node.borrow().right.as_ref() { Self::inorder_iterate(right, array); @@ -62,6 +62,5 @@ mod tests { use super::*; #[test] - fn test_98() { - } + fn test_98() {} } diff --git a/src/problem/p993_cousins_in_binary_tree.rs b/src/problem/p993_cousins_in_binary_tree.rs index 97000cb..0e631f3 100644 --- a/src/problem/p993_cousins_in_binary_tree.rs +++ b/src/problem/p993_cousins_in_binary_tree.rs @@ -3,7 +3,7 @@ */ pub struct Solution {} -use crate::util::tree::{TreeNode, to_tree}; +use crate::util::tree::{to_tree, TreeNode}; // submission codes start here @@ -25,8 +25,8 @@ use crate::util::tree::{TreeNode, to_tree}; // } // } // } -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; struct Tree { root: Rc>, @@ -35,7 +35,7 @@ struct Tree { x_parent: i32, y: i32, y_height: usize, - y_parent: i32 + y_parent: i32, } impl Tree { @@ -47,8 +47,8 @@ impl Tree { x_parent: 0, y, y_height: 0, - y_parent: 0 - } + y_parent: 0, + }; } fn dfs(&mut self, node: &Rc>, height: usize, parent: i32) { @@ -93,7 +93,6 @@ impl Solution { let mut tree = Tree::new(Rc::clone(&root), x, y); tree.dfs(&root, 0, -1); - tree.x_height == tree.y_height && tree.x_parent != tree.y_parent } } @@ -106,7 +105,10 @@ mod tests { #[test] fn test_993() { - assert!(!Solution::is_cousins(to_tree(vec![Some(1),Some(2),Some(3),Some(4)]), - 4, 3)); + assert!(!Solution::is_cousins( + to_tree(vec![Some(1), Some(2), Some(3), Some(4)]), + 4, + 3 + )); } } diff --git a/src/problem/p997_find_the_town_judge.rs b/src/problem/p997_find_the_town_judge.rs index 820559a..adbcda0 100644 --- a/src/problem/p997_find_the_town_judge.rs +++ b/src/problem/p997_find_the_town_judge.rs @@ -3,7 +3,6 @@ */ pub struct Solution {} - // submission codes start here impl Solution { diff --git a/src/problem/p9_palindrome_number.rs b/src/problem/p9_palindrome_number.rs index c6b55ad..21d68a1 100644 --- a/src/problem/p9_palindrome_number.rs +++ b/src/problem/p9_palindrome_number.rs @@ -4,28 +4,28 @@ * Given an integer x, return true if x is a palindrome, and false otherwise. * * Example 1: - * + * * Input: x = 121 * Output: true * Explanation: 121 reads as 121 from left to right and from right to left. - * + * * Example 2: - * + * * Input: x = -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: x = 10 * Output: false * Explanation: Reads 01 from right to left. Therefore it is not a palindrome. - * + * * * Constraints: - * + * * -2^31 <= x <= 2^31 - 1 - * + * * * Follow up: Could you solve it without converting the integer to a string? */ @@ -39,7 +39,7 @@ pub struct Solution {} impl Solution { pub fn is_palindrome(x: i32) -> bool { if x == 0 { - return true + return true; } if x < 0 || x % 10 == 0 { diff --git a/src/week_385/problem1.rs b/src/week_385/problem1.rs index 89b8a05..8c3f4e8 100644 --- a/src/week_385/problem1.rs +++ b/src/week_385/problem1.rs @@ -3,10 +3,8 @@ pub struct Solution; impl Solution { pub fn count_prefix_suffix_pairs(words: Vec) -> i32 { let mut result = 0; - let words: Vec> = words.iter() - .map(|s| {s.chars().collect()}) - .collect(); - + let words: Vec> = words.iter().map(|s| s.chars().collect()).collect(); + for j in 1..words.len() { for i in 0..j { if Solution::is_prefix_and_suffix(&words[i], &words[j]) { @@ -36,4 +34,4 @@ impl Solution { true } -} \ No newline at end of file +} diff --git a/src/week_385/problem2.rs b/src/week_385/problem2.rs index 41018cf..5e934e4 100644 --- a/src/week_385/problem2.rs +++ b/src/week_385/problem2.rs @@ -41,7 +41,5 @@ mod tests { use super::*; #[test] - fn test_385_2() { - - } -} \ No newline at end of file + fn test_385_2() {} +} diff --git a/src/week_416/mod.rs b/src/week_416/mod.rs index 5de73d0..4c1b159 100644 --- a/src/week_416/mod.rs +++ b/src/week_416/mod.rs @@ -1,2 +1,2 @@ mod problem1; -mod problem2; \ No newline at end of file +mod problem2; diff --git a/src/week_416/problem1.rs b/src/week_416/problem1.rs index 396fc52..b02c59e 100644 --- a/src/week_416/problem1.rs +++ b/src/week_416/problem1.rs @@ -3,24 +3,24 @@ pub struct Solution; impl Solution { pub fn report_spam(message: Vec, banned_words: Vec) -> bool { use std::collections::HashSet; - + let mut set = HashSet::with_capacity(banned_words.len()); for i in banned_words { set.insert(i); } - + let mut result = 0; - + for i in message.iter() { if set.contains(i) { result += 1; } - + if result >= 2 { return true; } } - + false } -} \ No newline at end of file +} diff --git a/src/week_416/problem2.rs b/src/week_416/problem2.rs index 8694a0b..0672c07 100644 --- a/src/week_416/problem2.rs +++ b/src/week_416/problem2.rs @@ -13,7 +13,7 @@ struct Worker { impl Ord for Worker { fn cmp(&self, other: &Self) -> Ordering { - (other.used_time + other.time).cmp(&(self.used_time + self.time)) + (other.used_time + other.time).cmp(&(self.used_time + self.time)) } } @@ -25,24 +25,28 @@ impl PartialOrd for Worker { impl Solution { pub fn min_number_of_seconds(mountain_height: i32, worker_times: Vec) -> i64 { - let mut worker_times: BinaryHeap = worker_times.iter().enumerate().map(|(i, v)| Worker { - time: *v as i64, - base_time: *v as i64, - used_time: 0, - count: 1, - }).collect(); - + let mut worker_times: BinaryHeap = worker_times + .iter() + .enumerate() + .map(|(i, v)| Worker { + time: *v as i64, + base_time: *v as i64, + used_time: 0, + count: 1, + }) + .collect(); + for _ in 0..mountain_height { let min_worker = worker_times.pop().unwrap(); - + worker_times.push(Worker { base_time: min_worker.base_time, count: min_worker.count + 1, used_time: min_worker.used_time + min_worker.time, - time: min_worker.base_time * (min_worker.count + 1) + time: min_worker.base_time * (min_worker.count + 1), }); } - + worker_times.iter().map(|w| w.used_time).max().unwrap() } } @@ -54,8 +58,8 @@ mod tests { #[test] fn test_416_2() { assert_eq!(10, Solution::min_number_of_seconds(5, vec![1, 5])); - assert_eq!(3, Solution::min_number_of_seconds(4, vec![2,1,1])); - assert_eq!(12, Solution::min_number_of_seconds(10, vec![3,2,2,4])); + assert_eq!(3, Solution::min_number_of_seconds(4, vec![2, 1, 1])); + assert_eq!(12, Solution::min_number_of_seconds(10, vec![3, 2, 2, 4])); assert_eq!(15, Solution::min_number_of_seconds(5, vec![1])); } }