20241024 finished.

This commit is contained in:
jackfiled 2024-10-24 09:08:13 +08:00
parent 3102da99a8
commit bce8de1c85
266 changed files with 2321 additions and 2014 deletions

View File

@ -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")

View File

@ -1,7 +1,7 @@
pub struct Solution;
use std::collections::BinaryHeap;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution {
pub fn min_operations(nums: Vec<i32>, k: i32) -> i32 {
@ -23,7 +23,6 @@ impl Solution {
result += 1;
}
result
}
}

View File

@ -5,7 +5,7 @@ use std::collections::HashMap;
impl Solution {
pub fn count_pairs_of_connectable_servers(edges: Vec<Vec<i32>>, signal_speed: i32) -> Vec<i32> {
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<Vec<(usize, i64)>>, conection: &mut Vec<(i64, usize)>, now: usize, pre: usize, distance: i64, start: usize) {
fn dfs(
graph: &Vec<Vec<(usize, i64)>>,
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<Vec<(usize, i64)>>, conection: &mut Vec<(i64, usize)>, result: &mut Vec<i32>,
now: usize, pre: usize, signal_speed: i64) {
fn tree_dp(
graph: &Vec<Vec<(usize, i64)>>,
conection: &mut Vec<(i64, usize)>,
result: &mut Vec<i32>,
now: usize,
pre: usize,
signal_speed: i64,
) {
let mut count = HashMap::new();
for node in conection {

View File

@ -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<CodeDefinition>,
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<StatWithStatus>
pub stat_status_pairs: Vec<StatWithStatus>,
}
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,13 +78,13 @@ 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 {

View File

@ -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<Problems, reqwest::Error> {
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<Problem, Box<dyn Error>> {
@ -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::<Query, Box<dyn Error>>("failed to get problem title slug".into())
}
Some(value) => {
Ok(Query::new(value.as_str()))
}
None => Err::<Query, Box<dyn Error>>(
"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::<RawProblem>()
.await?;
let title = problem.stat.question_title.clone()
let title = problem
.stat
.question_title
.clone()
.ok_or::<Box<dyn Error>>("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::<Box<dyn Error>>("failed to get problem title slug".into())?;
let return_type = {
let v = serde_json::from_str::<serde_json::Value>(
&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(_) => {}

View File

@ -1,6 +1,6 @@
use super::{Problem, ProblemManager};
use regex::Regex;
use std::fs;
use regex::{Regex};
impl ProblemManager {
pub fn scan() -> Result<ProblemManager, Box<dyn std::error::Error>> {
@ -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::<u32>() {
Ok(id) => {
problems.push(id);
}
Err(_) => {}
Some(value) => match value.as_str().parse::<u32>() {
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<String, Box<dyn std::error::Error>> {
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::<Box<dyn std::error::Error>>(
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)

View File

@ -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;

View File

@ -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.");
}

View File

@ -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<i32>) -> Vec<i32> {
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]);
}
}

View File

@ -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>) -> 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);
}
}

View File

@ -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 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 p908_smallest_range_i;
mod p910_smallest_range_ii;
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 p977_squares_of_a_sorted_array;
mod p983_minimum_cost_for_tickets;
mod p997_find_the_town_judge;

View File

@ -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<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> bool {
pub fn is_same_tree(
p: Option<Rc<RefCell<TreeNode>>>,
q: Option<Rc<RefCell<TreeNode>>>,
) -> bool {
let mut p_queue = VecDeque::new();
let mut q_queue = VecDeque::new();
@ -90,6 +93,5 @@ mod tests {
use super::*;
#[test]
fn test_100() {
}
fn test_100() {}
}

View File

@ -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<Rc<RefCell<TreeNode>>>, right: &Option<Rc<RefCell<TreeNode>>>) -> bool {
fn is_same(
left: &Option<Rc<RefCell<TreeNode>>>,
right: &Option<Rc<RefCell<TreeNode>>>,
) -> bool {
if left.is_some() ^ right.is_some() {
return false;
}
@ -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
)))
}
}

View File

@ -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<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
@ -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]]
);
}
}

View File

@ -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<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
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]]
);
}
}

View File

@ -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<i32>, inorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
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)
])
);
}
}

View File

@ -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<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
@ -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]]
);
}
}

View File

@ -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 sorted_array_to_bst(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
Some(Self::array_to_bst(&nums[..]))
@ -65,6 +65,5 @@ mod tests {
use super::*;
#[test]
fn test_108() {
}
fn test_108() {}
}

View File

@ -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<RefCell<TreeNode>>, current_sum: i32, target_sum: i32) -> bool {
// 到达叶子节点
@ -49,7 +49,6 @@ impl Solution {
false
}
pub fn has_path_sum(root: Option<Rc<RefCell<TreeNode>>>, 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() {}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -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)
);
}
}

View File

@ -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]])
);
}
}

View File

@ -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]));
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {

View File

@ -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 max_sum(node: &Rc<RefCell<TreeNode>>, result: &mut i32) -> i32 {
if node.borrow().left.is_none() && node.borrow().right.is_none() {
@ -39,13 +39,15 @@ impl Solution {
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() {}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -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()));
}
}

View File

@ -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<i32>
collected_set: HashSet<i32>,
}
/**
* `&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<Rc<RefCell<TreeNode>>>) -> Self {
let mut queue = VecDeque::new();
let mut collected_set = HashSet::new();
@ -61,9 +59,7 @@ impl FindElements {
};
}
FindElements {
collected_set
}
FindElements { collected_set }
}
fn find(&self, target: i32) -> bool {
@ -84,6 +80,5 @@ mod tests {
use super::*;
#[test]
fn test_1261() {
}
fn test_1261() {}
}

View File

@ -42,15 +42,13 @@ pub struct Solution {}
impl Solution {
pub fn num_of_burgers(tomato_slices: i32, cheese_slices: i32) -> Vec<i32> {
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,7 +63,7 @@ impl Solution {
}
if tomato * cheese == 0f32 {
return vec![]
return vec![];
}
}
@ -81,7 +79,7 @@ mod tests {
#[test]
fn test_1276() {
let empty_array : Vec<i32> = Vec::new();
let empty_array: Vec<i32> = 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));

View File

@ -58,37 +58,37 @@ impl Solution {
// 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 {
@ -141,35 +141,42 @@ 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!["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!["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
);
}
}

View File

@ -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<RefCell<TreeNode>>, 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<Rc<RefCell<TreeNode>>>) -> 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() {}
}

View File

@ -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() {}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {

View File

@ -3,16 +3,15 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn single_number(nums: Vec<i32>) -> 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

View File

@ -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")
));
}
}

View File

@ -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")
])
);
}
}

View File

@ -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<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
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]
);
}
}

View File

@ -3,30 +3,25 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn busy_student(start_time: Vec<i32>, end_time: Vec<i32>, 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
}

View File

@ -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<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
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]
);
}
}

View File

@ -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 {
@ -62,7 +58,7 @@ impl Solution {
}
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);

View File

@ -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", "*"]));
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -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())
);
}
}

View File

@ -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() {}
}

View File

@ -3,26 +3,23 @@
*/
pub struct Solution {}
// submission codes start here
use std::{cmp::Reverse, collections::BinaryHeap};
struct MinStack {
heap : BinaryHeap<Reverse<i32>>,
stack: Vec<i32>
heap: BinaryHeap<Reverse<i32>>,
stack: Vec<i32>,
}
/**
* `&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![],
}
}
@ -64,6 +61,5 @@ mod tests {
use super::*;
#[test]
fn test_155() {
}
fn test_155() {}
}

View File

@ -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]));
}
}

View File

@ -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));
}
}

View File

@ -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<i32>, bob_values: Vec<i32>) -> i32 {
let mut stones: Vec<Stone> = alice_values.iter()
let mut stones: Vec<Stone> = 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);
}
}

View File

@ -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);
}
}

View File

@ -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<i32>, 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
);
}
}

View File

@ -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]));
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -27,6 +26,5 @@ mod tests {
use super::*;
#[test]
fn test_172() {
}
fn test_172() {}
}

View File

@ -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<Rc<RefCell<TreeNode>>>
stack: Vec<Rc<RefCell<TreeNode>>>,
}
/**
@ -40,12 +40,9 @@ struct BSTIterator {
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl BSTIterator {
fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {
if root.is_none() {
return BSTIterator {
stack: vec![]
};
return BSTIterator { stack: vec![] };
}
let mut stack = vec![];
@ -64,10 +61,7 @@ impl BSTIterator {
node = left;
}
BSTIterator {
stack
}
BSTIterator { stack }
}
fn next(&mut self) -> i32 {
@ -112,6 +106,5 @@ mod tests {
use super::*;
#[test]
fn test_173() {
}
fn test_173() {}
}

View File

@ -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));
}
}

View File

@ -3,13 +3,13 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn letter_combinations(digits: String) -> Vec<String> {
let mut result = vec![];
let digits: Vec<usize> = digits.chars()
let digits: Vec<usize> = digits
.chars()
.map(|c| (c.to_digit(10).unwrap() - 2) as usize)
.collect();
let mut str = Vec::with_capacity(digits.len());

View File

@ -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<Reverse<i32>>
seats: BinaryHeap<Reverse<i32>>,
}
/**
@ -16,7 +16,6 @@ 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);
@ -24,9 +23,7 @@ impl SeatManager {
heap.push(Reverse(i));
}
Self {
seats: heap
}
Self { seats: heap }
}
fn reserve(&mut self) -> i32 {

View File

@ -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));

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -19,6 +18,5 @@ mod tests {
use super::*;
#[test]
fn test_190() {
}
fn test_190() {}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -39,7 +38,7 @@ impl Solution {
1 << 3,
1 << 2,
1 << 1,
1
1,
];
let mut result = 0;

View File

@ -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];
@ -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() {}
}

View File

@ -5,7 +5,6 @@ use std::convert::TryInto;
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -20,7 +19,9 @@ impl Solution {
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 {

View File

@ -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,7 +28,7 @@ impl Solution {
pub fn count_paths(n: i32, roads: Vec<Vec<i32>>) -> 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;
@ -40,13 +39,16 @@ 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();
@ -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() {}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {

View File

@ -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>) -> 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() {}
}

View File

@ -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<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![];
@ -68,6 +68,5 @@ mod tests {
use super::*;
#[test]
fn test_199() {
}
fn test_199() {}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -56,6 +55,5 @@ mod tests {
use super::*;
#[test]
fn test_200() {
}
fn test_200() {}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {

View File

@ -3,17 +3,16 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn max_consecutive_answers(answer_key: String, k: i32) -> i32 {
let str : Vec<char> = answer_key.chars().collect();
let str: Vec<char> = 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<char>, k: i32, c : char) -> i32 {
fn max_consecutive_char(str: &Vec<char>, k: i32, c: char) -> i32 {
let n = str.len();
let mut result = 0;
@ -21,13 +20,13 @@ impl Solution {
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;
}

View File

@ -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() {}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -13,11 +12,7 @@ impl Solution {
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;
@ -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));
}
}

View File

@ -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<Vec<i32>>) -> 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);
@ -51,6 +50,5 @@ mod tests {
use super::*;
#[test]
fn test_207() {
}
fn test_207() {}
}

View File

@ -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() {}
}

View File

@ -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() {}
}

View File

@ -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;
}
}

View File

@ -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<i32>>) -> Vec<i32> {
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() {}
}

View File

@ -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;
}

View File

@ -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())
);
}
}

View File

@ -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<Vec<char>>, node: &Rc<RefCell<TrieNode>>, words: &Vec<String>, result: &mut HashSet<String>,
visited: &mut Vec<Vec<bool>>, x: i32, y: i32) {
fn dfs(
board: &Vec<Vec<char>>,
node: &Rc<RefCell<TrieNode>>,
words: &Vec<String>,
result: &mut HashSet<String>,
visited: &mut Vec<Vec<bool>>,
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 {
@ -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");
@ -136,7 +148,7 @@ mod tests {
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");

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {

View File

@ -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);
}
}

View File

@ -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]))
);
}
}

View File

@ -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)
);
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -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));
}
}

View File

@ -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,7 +20,6 @@ impl Solution {
} else {
*last_pos = i as i32;
}
} else {
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
));
}
}

View File

@ -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<Box<ListNode>>, list2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
pub fn merge_two_lists(
list1: Option<Box<ListNode>>,
list2: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
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() {}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -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())
);
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -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']]));
}
}

View File

@ -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<Rc<RefCell<TreeNode>>>) -> i32 {
let mut result = 0;
@ -62,6 +62,5 @@ mod tests {
use super::*;
#[test]
fn test_222() {
}
fn test_222() {}
}

View File

@ -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<char> = s.chars().collect();
let s: Vec<char> = s.chars().collect();
let mut i = 0;

View File

@ -3,25 +3,22 @@
*/
pub struct Solution {}
// submission codes start here
use std::collections::VecDeque;
struct MyStack {
queue: VecDeque<i32>
queue: VecDeque<i32>,
}
/**
* `&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) {

View File

@ -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,19 +25,15 @@ 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<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
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;

View File

@ -3,14 +3,13 @@
*/
pub struct Solution {}
// submission codes start here
struct BookMyShow {
row_count: i32,
column_count: i32,
min_tree: Vec<i32>,
sum_tree: Vec<i64>
sum_tree: Vec<i64>,
}
/**
@ -24,7 +23,7 @@ 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],
}
}
@ -52,7 +51,7 @@ impl BookMyShow {
self.row_count
} else {
l
}
};
}
let middle = (l + r) / 2;
@ -134,7 +133,7 @@ mod tests {
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::<i32>::new(), show.gather(2, 0));
assert!(show.scatter(5, 1));
assert!(!show.scatter(5, 1));

View File

@ -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() {}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -45,6 +44,5 @@ mod tests {
use super::*;
#[test]
fn test_22() {
}
fn test_22() {}
}

View File

@ -3,12 +3,11 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn distinct_names(ideas: Vec<String>) -> i64 {
use std::collections::{HashSet, HashMap};
use std::collections::{HashMap, HashSet};
let mut map = HashMap::new();
@ -24,7 +23,8 @@ impl Solution {
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
}
}
@ -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")));
}
}

View File

@ -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<RefCell<TreeNode>>, count: &mut i32, target: i32) -> Option<i32> {
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() {}
}

View File

@ -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() {}
}

View File

@ -3,26 +3,23 @@
*/
pub struct Solution {}
// submission codes start here
use std::collections::VecDeque;
struct MyQueue {
in_stack: VecDeque<i32>,
out_stack: VecDeque<i32>
out_stack: VecDeque<i32>,
}
/**
* `&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(),
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -36,7 +35,7 @@ impl Solution {
// 最后一个上车的哥们
let mut down_passenger = if last_passenger == 0 {
// 特判一下如果没有哥们可以上车的情况
return buses[n - 1]
return buses[n - 1];
} else {
last_passenger - 1
};
@ -61,7 +60,6 @@ impl Solution {
result
};
loop {
if result != passengers[down_passenger] {
break;
@ -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));

View File

@ -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,17 +25,25 @@ 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<Rc<RefCell<TreeNode>>>, p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
pub fn lowest_common_ancestor(
root: Option<Rc<RefCell<TreeNode>>>,
p: Option<Rc<RefCell<TreeNode>>>,
q: Option<Rc<RefCell<TreeNode>>>,
) -> Option<Rc<RefCell<TreeNode>>> {
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;
@ -53,6 +61,5 @@ mod tests {
use super::*;
#[test]
fn test_235() {
}
fn test_235() {}
}

Some files were not shown because too many files have changed in this diff Show More