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 build: update
cargo build --release cargo build --release
test: fmt:
cargo fmt
test: fmt
cargo test cargo test
commit: commit: test
#!/usr/bin/env bash #!/usr/bin/env bash
set -euxo pipefail set -euxo pipefail
time=$(date "+%Y%m%d") time=$(date "+%Y%m%d")

View File

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

View File

@ -5,7 +5,7 @@ use std::collections::HashMap;
impl Solution { impl Solution {
pub fn count_pairs_of_connectable_servers(edges: Vec<Vec<i32>>, signal_speed: i32) -> Vec<i32> { pub fn count_pairs_of_connectable_servers(edges: Vec<Vec<i32>>, signal_speed: i32) -> Vec<i32> {
let n = edges.len(); let n = edges.len();
let mut graph = vec![vec![];n]; let mut graph = vec![vec![]; n];
let signal_speed = signal_speed as i64; let signal_speed = signal_speed as i64;
for edge in &edges { for edge in &edges {
@ -17,17 +17,22 @@ impl Solution {
graph[y].push((x, weight)); graph[y].push((x, weight));
} }
let mut connection = vec![(0,0);n]; let mut connection = vec![(0, 0); n];
for next in &graph[0] { for next in &graph[0] {}
}
let mut result = Vec::with_capacity(n); let mut result = Vec::with_capacity(n);
result 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] { for next in &graph[now] {
if next.0 == pre { if next.0 == pre {
continue; continue;
@ -39,8 +44,14 @@ impl Solution {
} }
} }
fn tree_dp(graph: &Vec<Vec<(usize, i64)>>, conection: &mut Vec<(i64, usize)>, result: &mut Vec<i32>, fn tree_dp(
now: usize, pre: usize, signal_speed: i64) { 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(); let mut count = HashMap::new();
for node in conection { for node in conection {

View File

@ -9,7 +9,7 @@ pub struct CodeDefinition {
pub value: String, pub value: String,
pub text: String, pub text: String,
#[serde(rename = "defaultCode")] #[serde(rename = "defaultCode")]
pub default_code: String pub default_code: String,
} }
/// LeetCode 单个问题 /// LeetCode 单个问题
@ -19,7 +19,7 @@ pub struct Problem {
pub content: String, pub content: String,
pub code_definition: Vec<CodeDefinition>, pub code_definition: Vec<CodeDefinition>,
pub question_id: u32, pub question_id: u32,
pub return_type: String pub return_type: String,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@ -47,7 +47,7 @@ pub struct StatWithStatus {
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct Problems { pub struct Problems {
pub stat_status_pairs: Vec<StatWithStatus> pub stat_status_pairs: Vec<StatWithStatus>,
} }
const QUESTION_QUERY_STRING: &str = r#" const QUESTION_QUERY_STRING: &str = r#"
@ -68,7 +68,7 @@ pub struct Query {
#[serde(rename = "operationName")] #[serde(rename = "operationName")]
operation_name: String, operation_name: String,
variables: serde_json::Value, variables: serde_json::Value,
query: String query: String,
} }
impl Query { impl Query {
@ -78,13 +78,13 @@ impl Query {
variables: json!({ variables: json!({
"titleSlug": title "titleSlug": title
}), }),
query: QUESTION_QUERY_STRING.to_owned() query: QUESTION_QUERY_STRING.to_owned(),
} }
} }
} }
pub struct Fetcher { pub struct Fetcher {
client: reqwest::Client client: reqwest::Client,
} }
pub struct ProblemManager { 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 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 PROBLEMS_URL: &str = "https://leetcode.cn/api/problems/algorithms/";
const GRAPHQL_URL: &str = "https://leetcode.cn/graphql"; const GRAPHQL_URL: &str = "https://leetcode.cn/graphql";
@ -8,16 +8,12 @@ const GRAPHQL_URL: &str = "https://leetcode.cn/graphql";
impl Fetcher { impl Fetcher {
pub fn new() -> Fetcher { pub fn new() -> Fetcher {
Fetcher { Fetcher {
client: reqwest::Client::new() client: reqwest::Client::new(),
} }
} }
pub async fn get_problems(&self) -> Result<Problems, reqwest::Error> { pub async fn get_problems(&self) -> Result<Problems, reqwest::Error> {
Ok(reqwest::get(PROBLEMS_URL) Ok(reqwest::get(PROBLEMS_URL).await?.json().await?)
.await?
.json()
.await?
)
} }
pub async fn get_problem(self, question_id: u32) -> Result<Problem, Box<dyn Error>> { pub async fn get_problem(self, question_id: u32) -> Result<Problem, Box<dyn Error>> {
@ -28,19 +24,18 @@ impl Fetcher {
Ok(id) => { Ok(id) => {
if id == question_id { if id == question_id {
if problem.paid_only { 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 { let query = match &problem.stat.question_title_slug {
None => { None => Err::<Query, Box<dyn Error>>(
Err::<Query, Box<dyn Error>>("failed to get problem title slug".into()) "failed to get problem title slug".into(),
} ),
Some(value) => { Some(value) => Ok(Query::new(value.as_str())),
Ok(Query::new(value.as_str()))
}
}?; }?;
let response = self.client let response = self
.client
.post(GRAPHQL_URL) .post(GRAPHQL_URL)
.json(&query) .json(&query)
.send() .send()
@ -48,20 +43,24 @@ impl Fetcher {
.json::<RawProblem>() .json::<RawProblem>()
.await?; .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())?; .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())?; .ok_or::<Box<dyn Error>>("failed to get problem title slug".into())?;
let return_type = { let return_type = {
let v = serde_json::from_str::<serde_json::Value>( let v = serde_json::from_str::<serde_json::Value>(
&response.data.question.meta_data); &response.data.question.meta_data,
v.and_then(|x| { );
return Ok(x.to_string().replace("\"", "")) v.and_then(|x| return Ok(x.to_string().replace("\"", "")))
})
}?; }?;
let code_definition = serde_json::from_str( let code_definition =
&response.data.question.code_definition serde_json::from_str(&response.data.question.code_definition)?;
)?;
return Ok(Problem { return Ok(Problem {
title, title,
@ -69,8 +68,8 @@ impl Fetcher {
code_definition, code_definition,
content: response.data.question.content, content: response.data.question.content,
question_id: id, question_id: id,
return_type return_type,
}) });
} }
} }
Err(_) => {} Err(_) => {}

View File

@ -1,6 +1,6 @@
use super::{Problem, ProblemManager}; use super::{Problem, ProblemManager};
use regex::Regex;
use std::fs; use std::fs;
use regex::{Regex};
impl ProblemManager { impl ProblemManager {
pub fn scan() -> Result<ProblemManager, Box<dyn std::error::Error>> { pub fn scan() -> Result<ProblemManager, Box<dyn std::error::Error>> {
@ -11,45 +11,43 @@ impl ProblemManager {
for i in pattern.captures_iter(&mod_content) { for i in pattern.captures_iter(&mod_content) {
match i.get(1) { match i.get(1) {
None => {} None => {}
Some(value) => { Some(value) => match value.as_str().parse::<u32>() {
match value.as_str().parse::<u32>() {
Ok(id) => { Ok(id) => {
problems.push(id); problems.push(id);
} }
Err(_) => {} Err(_) => {}
} },
}
} }
} }
Ok(ProblemManager { Ok(ProblemManager {
problem_list: problems problem_list: problems,
}) })
} }
} }
impl Problem { impl Problem {
pub fn get_filename(&self) -> String { 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>> { pub fn get_file_content(&self) -> Result<String, Box<dyn std::error::Error>> {
let template = fs::read_to_string("./template.rs")?; let template = fs::read_to_string("./template.rs")?;
let code = self.code_definition let code = self.code_definition.iter().find(|x| x.value == "rust");
.iter()
.find(|x| x.value == "rust");
let code = code.ok_or::<Box<dyn std::error::Error>>( 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 let source = template
.replace("__PROBLEM_TITLE__", &self.title) .replace("__PROBLEM_TITLE__", &self.title)
.replace("__PROBLEM_ID__", self.question_id.to_string().as_str()) .replace("__PROBLEM_ID__", self.question_id.to_string().as_str())
.replace( .replace("__PROBLEM_DEFAULT_CODE__", &code.default_code)
"__PROBLEM_DEFAULT_CODE__",
&code.default_code)
.replace("__EXTRA_USE__", &parse_extra_use(&code.default_code)); .replace("__EXTRA_USE__", &parse_extra_use(&code.default_code));
Ok(source) Ok(source)

View File

@ -1,6 +1,6 @@
#[macro_use] #[macro_use]
pub mod util; pub mod util;
pub mod double_week_125;
pub mod problem; pub mod problem;
pub mod week_385; pub mod week_385;
pub mod week_416; 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::fs;
use std::io::Write; use std::io::Write;
use std::path::Path; use std::path::Path;
use crate::fetch_problem::{Fetcher, ProblemManager};
mod fetch_problem; mod fetch_problem;
@ -22,12 +22,16 @@ async fn main() {
println!("Try to get problem {}...", id); 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)); .expect(&*format!("Failed to get problem {}.", id));
let file_name = problem.get_filename(); let file_name = problem.get_filename();
println!("Get problem: {}.", file_name); 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."); write_file(&file_name, &content).expect("Failed to write problem file.");
} }

View File

@ -1,15 +1,14 @@
pub struct Solution {} pub struct Solution {}
use std::collections::BinaryHeap;
use std::cmp::Reverse; use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution { impl Solution {
pub fn nums_game(nums: Vec<i32>) -> Vec<i32> { pub fn nums_game(nums: Vec<i32>) -> Vec<i32> {
let mut result = Vec::with_capacity(nums.len()); let mut result = Vec::with_capacity(nums.len());
let m = 1000000007i64; let m = 1000000007i64;
let (mut lower, mut upper) = let (mut lower, mut upper) = (BinaryHeap::new(), BinaryHeap::new());
(BinaryHeap::new(), BinaryHeap::new());
let (mut lower_sum, mut upper_sum) = (0i64, 0i64); let (mut lower_sum, mut upper_sum) = (0i64, 0i64);
for (index, value) in nums.iter().enumerate() { for (index, value) in nums.iter().enumerate() {
@ -41,10 +40,9 @@ impl Solution {
} }
if (index + 1) % 2 == 0 { if (index + 1) % 2 == 0 {
result.push(((upper_sum - lower_sum) % m) as i32 ); result.push(((upper_sum - lower_sum) % m) as i32);
} else { } else {
result.push(((upper_sum - lower_sum + *lower.peek().unwrap() as i64) result.push(((upper_sum - lower_sum + *lower.peek().unwrap() as i64) % m) as i32);
% m) as i32);
} }
} }
@ -58,8 +56,14 @@ mod tests {
#[test] #[test]
fn test_lcp24() { fn test_lcp24() {
assert_eq!(Solution::nums_game(vec![3,4,5,1,6,7]), vec![0,0,0,5,6,7]); assert_eq!(
assert_eq!(Solution::nums_game(vec![1,2,3,4,5]), vec![0,0,0,0,0]); Solution::nums_game(vec![3, 4, 5, 1, 6, 7]),
assert_eq!(Solution::nums_game(vec![471, 626, 848]), vec![0, 154,375]); 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 {} pub struct Solution {}
use std::collections::BinaryHeap;
use std::cmp::Reverse; use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution { impl Solution {
pub fn magic_tower(nums: Vec<i32>) -> i32 { pub fn magic_tower(nums: Vec<i32>) -> i32 {
@ -41,9 +41,10 @@ mod tests {
#[test] #[test]
fn test_lcp30() { fn test_lcp30() {
assert_eq!(Solution::magic_tower( assert_eq!(
vec![100,100,100,-250,-60,-140,-50,-50,100,150]), 1); Solution::magic_tower(vec![100, 100, 100, -250, -60, -140, -50, -50, 100, 150]),
assert_eq!(Solution::magic_tower( 1
vec![-200,-300,400,0]), -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 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 lcp30_magic_tower;
mod p2641_cousins_in_binary_tree_ii; mod p100_same_tree;
mod p993_cousins_in_binary_tree; mod p101_symmetric_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 p102_binary_tree_level_order_traversal; mod p102_binary_tree_level_order_traversal;
mod p107_binary_tree_level_order_traversal_ii;
mod p103_binary_tree_zigzag_level_order_traversal; 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 p105_construct_binary_tree_from_preorder_and_inorder_traversal;
mod p106_construct_binary_tree_from_inorder_and_postorder_traversal; mod p106_construct_binary_tree_from_inorder_and_postorder_traversal;
mod p235_lowest_common_ancestor_of_a_binary_search_tree; mod p107_binary_tree_level_order_traversal_ii;
mod p2583_kth_largest_sum_in_a_binary_tree; mod p108_convert_sorted_array_to_binary_search_tree;
mod p2476_closest_nodes_queries_in_a_binary_search_tree; mod p112_path_sum;
mod p938_range_sum_of_bst; mod p114_flatten_binary_tree_to_linked_list;
mod p889_construct_binary_tree_from_preorder_and_postorder_traversal; mod p120_triangle;
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 p121_best_time_to_buy_and_sell_stock; mod p121_best_time_to_buy_and_sell_stock;
mod p122_best_time_to_buy_and_sell_stock_ii; mod p122_best_time_to_buy_and_sell_stock_ii;
mod p55_jump_game; mod p123_best_time_to_buy_and_sell_stock_iii;
mod p45_jump_game_ii; mod p124_binary_tree_maximum_path_sum;
mod p274_h_index; mod p125_valid_palindrome;
mod p380_insert_delete_getrandom_o1; mod p1261_find_elements_in_a_contaminated_binary_tree;
mod p238_product_of_array_except_self; 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 p134_gas_station;
mod p135_candy; 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 p136_single_number;
mod p137_single_number_ii; 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 p139_word_break;
mod p300_longest_increasing_subsequence; mod p144_binary_tree_preorder_traversal;
mod p120_triangle; mod p145_binary_tree_postorder_traversal;
mod p64_minimum_path_sum; mod p149_max_points_on_a_line;
mod p63_unique_paths_ii; mod p150_evaluate_reverse_polish_notation;
mod p97_interleaving_string; mod p151_reverse_words_in_a_string;
mod p72_edit_distance; mod p153_find_minimum_in_rotated_sorted_array;
mod p123_best_time_to_buy_and_sell_stock_iii; 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 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 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 p3117_minimum_sum_of_values_by_dividing_array;
mod p3137_minimum_number_of_operations_to_make_word_k_periodic; 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 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 p1184_distance_between_bus_stops;
mod p3154_find_number_of_ways_to_reach_the_k_th_stair; mod p1227_airplane_seat_assignment_probability;
mod p3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k; mod p1436_destination_city;
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 p1450_number_of_students_doing_homework_at_a_given_time; 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 p2024_maximize_the_confusion_of_an_exam;
mod p2708_maximum_strength_of_a_group; mod p2073_time_needed_to_buy_tickets;
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 p2181_merge_nodes_in_between_zeros; 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 p2552_count_increasing_quadruplets;
mod p2555_maximize_win_from_two_segments; mod p2555_maximize_win_from_two_segments;
mod p2576_find_the_maximum_number_of_marked_indices; mod p2576_find_the_maximum_number_of_marked_indices;
mod p2398_maximum_number_of_robots_within_budget; mod p2708_maximum_strength_of_a_group;
mod p2390_removing_stars_from_a_string;
mod p2848_points_that_intersect_with_cars; mod p2848_points_that_intersect_with_cars;
mod p1184_distance_between_bus_stops; mod p2860_happy_students;
mod p815_bus_routes; mod p3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k;
mod p2332_the_latest_time_to_catch_a_bus; mod p3127_make_a_square_with_the_same_color;
mod p2414_length_of_the_longest_alphabetical_continuous_substring; mod p3133_minimum_array_end;
mod p2376_count_special_integers; mod p3134_find_the_median_of_the_uniqueness_array;
mod p2374_node_with_highest_edge_score; mod p3142_check_if_grid_satisfies_conditions;
mod p997_find_the_town_judge; mod p3144_minimum_substring_partition_of_equal_character_frequency;
mod p2207_maximize_number_of_subsequences_in_a_string; mod p3145_find_products_of_elements_of_big_array;
mod p2306_naming_a_company; mod p3146_permutation_difference_between_two_strings;
mod p2535_difference_between_element_sum_and_digit_sum_of_an_array; mod p3153_sum_of_digit_differences_of_all_pairs;
mod p2516_take_k_of_each_character_from_left_and_right; mod p3154_find_number_of_ways_to_reach_the_k_th_stair;
mod p2286_booking_concert_tickets_in_groups; mod p3158_find_the_xor_of_numbers_which_appear_twice;
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 p3162_find_the_number_of_good_pairs_i; mod p3162_find_the_number_of_good_pairs_i;
mod p3164_find_the_number_of_good_pairs_ii; mod p3164_find_the_number_of_good_pairs_ii;
mod p3158_find_the_xor_of_numbers_which_appear_twice; mod p3171_find_subarray_with_bitwise_or_closest_to_k;
mod p1884_egg_drop_with_2_eggs_and_n_floors; mod p3174_clear_digits;
mod p887_super_egg_drop; mod p3175_find_the_first_player_to_win_k_games_in_a_row;
mod p3200_maximum_height_of_a_triangle; mod p3176_find_the_maximum_length_of_a_good_subsequence_i;
mod p3194_minimum_average_of_smallest_and_largest_elements; mod p3177_find_the_maximum_length_of_a_good_subsequence_ii;
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 p3184_count_pairs_that_form_a_complete_day_i; mod p3184_count_pairs_that_form_a_complete_day_i;
mod p3185_count_pairs_that_form_a_complete_day_ii; 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 {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution { 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 p_queue = VecDeque::new();
let mut q_queue = VecDeque::new(); let mut q_queue = VecDeque::new();
@ -90,6 +93,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_100() { fn test_100() {}
}
} }

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::rc::Rc;
impl Solution { 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() { if left.is_some() ^ right.is_some() {
return false; return false;
} }
@ -65,7 +68,9 @@ mod tests {
#[test] #[test]
fn test_101() { fn test_101() {
assert!(Solution::is_symmetric(tree![1,2,2,3,4,4,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))) assert!(!Solution::is_symmetric(tree!(
1, 2, 2, "null", 3, "null", 3
)))
} }
} }

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::rc::Rc;
impl Solution { impl Solution {
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> { pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
@ -72,8 +72,17 @@ mod tests {
#[test] #[test]
fn test_102() { fn test_102() {
assert_eq!(Solution::level_order( assert_eq!(
to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)]) Solution::level_order(to_tree(vec![
), vec![vec![3], vec![9, 20], vec![15, 7]]); 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 {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::rc::Rc;
impl Solution { impl Solution {
pub fn zigzag_level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> { pub fn zigzag_level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
let root = if let Some(r) = root { let root = if let Some(r) = root {
@ -77,8 +77,17 @@ mod tests {
#[test] #[test]
fn test_103() { fn test_103() {
assert_eq!(Solution::zigzag_level_order( assert_eq!(
to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)]) Solution::zigzag_level_order(to_tree(vec![
), vec![vec![3], vec![20, 9], vec![15, 7]]); 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 surf::middleware::logger::new;
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::rc::Rc;
impl Solution { impl Solution {
pub fn build_tree(preorder: Vec<i32>, inorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> { pub fn build_tree(preorder: Vec<i32>, inorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
if preorder.len() == 0 { if preorder.len() == 0 {
return None; return None;
} }
let root = Rc::new(RefCell::new( let root = Rc::new(RefCell::new(TreeNode::new(preorder[0])));
TreeNode::new(preorder[0])));
let mut stack = Vec::new(); let mut stack = Vec::new();
stack.push(Rc::clone(&root)); stack.push(Rc::clone(&root));
let mut inorder_index = 0; let mut inorder_index = 0;
@ -45,8 +44,7 @@ impl Solution {
let mut node = Rc::clone(stack.last().unwrap()); let mut node = Rc::clone(stack.last().unwrap());
if node.borrow().val != inorder[inorder_index] { if node.borrow().val != inorder[inorder_index] {
let new_node = Rc::new(RefCell::new( let new_node = Rc::new(RefCell::new(TreeNode::new(preorder[i])));
TreeNode::new(preorder[i])));
stack.push(Rc::clone(&new_node)); stack.push(Rc::clone(&new_node));
node.borrow_mut().left = Some(new_node); node.borrow_mut().left = Some(new_node);
} else { } else {
@ -60,8 +58,7 @@ impl Solution {
} }
} }
let new_node = Rc::new(RefCell::new( let new_node = Rc::new(RefCell::new(TreeNode::new(preorder[i])));
TreeNode::new(preorder[i])));
stack.push(Rc::clone(&new_node)); stack.push(Rc::clone(&new_node));
node.borrow_mut().right = Some(new_node); node.borrow_mut().right = Some(new_node);
} }
@ -79,9 +76,17 @@ mod tests {
#[test] #[test]
fn test_105() { fn test_105() {
assert_eq!(Solution::build_tree( assert_eq!(
vec![3,9,20,15,7], Solution::build_tree(vec![3, 9, 20, 15, 7], vec![9, 3, 15, 20, 7]),
vec![9,3,15,20,7]), to_tree(vec![
to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)])); Some(3),
Some(9),
Some(20),
None,
None,
Some(15),
Some(7)
])
);
} }
} }

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::rc::Rc;
impl Solution { impl Solution {
pub fn level_order_bottom(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> { pub fn level_order_bottom(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
@ -73,8 +73,17 @@ mod tests {
#[test] #[test]
fn test_107() { fn test_107() {
assert_eq!(Solution::level_order_bottom( assert_eq!(
to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)]) Solution::level_order_bottom(to_tree(vec![
), vec![vec![15, 7], vec![9, 20], vec![3]]); 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 {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::rc::Rc;
impl Solution { impl Solution {
pub fn sorted_array_to_bst(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> { pub fn sorted_array_to_bst(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
Some(Self::array_to_bst(&nums[..])) Some(Self::array_to_bst(&nums[..]))
@ -65,6 +65,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_108() { fn test_108() {}
}
} }

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::rc::Rc;
impl Solution { impl Solution {
fn dfs(node: &Rc<RefCell<TreeNode>>, current_sum: i32, target_sum: i32) -> bool { fn dfs(node: &Rc<RefCell<TreeNode>>, current_sum: i32, target_sum: i32) -> bool {
// 到达叶子节点 // 到达叶子节点
@ -49,7 +49,6 @@ impl Solution {
false false
} }
pub fn has_path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> bool { pub fn has_path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> bool {
if let Some(root) = root { if let Some(root) = root {
return Self::dfs(&root, 0, target_sum); return Self::dfs(&root, 0, target_sum);
@ -66,6 +65,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_112() { fn test_112() {}
}
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -39,8 +38,17 @@ mod tests {
#[test] #[test]
fn test_1184() { fn test_1184() {
assert_eq!(1, Solution::distance_between_bus_stops(vec![1,2,3,4], 0, 1)); assert_eq!(
assert_eq!(3, Solution::distance_between_bus_stops(vec![1,2,3,4],0, 2)); 1,
assert_eq!(4, Solution::distance_between_bus_stops(vec![1,2,3,4],0,3)); 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -37,6 +36,9 @@ mod tests {
#[test] #[test]
fn test_120() { 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -33,6 +32,6 @@ mod tests {
#[test] #[test]
fn test_121() { 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {

View File

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

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::rc::Rc;
impl Solution { impl Solution {
fn max_sum(node: &Rc<RefCell<TreeNode>>, result: &mut i32) -> i32 { fn max_sum(node: &Rc<RefCell<TreeNode>>, result: &mut i32) -> i32 {
if node.borrow().left.is_none() && node.borrow().right.is_none() { if node.borrow().left.is_none() && node.borrow().right.is_none() {
@ -39,13 +39,15 @@ impl Solution {
Self::max_sum(left, result) Self::max_sum(left, result)
} else { } else {
0 0
}.max(0); }
.max(0);
let right_sum = if let Some(right) = &node.borrow().right { let right_sum = if let Some(right) = &node.borrow().right {
Self::max_sum(right, result) Self::max_sum(right, result)
} else { } else {
0 0
}.max(0); }
.max(0);
*result = (*result).max(node.borrow().val + left_sum + right_sum); *result = (*result).max(node.borrow().val + left_sum + right_sum);
@ -70,6 +72,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_124() { fn test_124() {}
}
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -45,7 +44,9 @@ mod tests {
#[test] #[test]
fn test_125() { 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())); assert!(!Solution::is_palindrome("0P".to_owned()));
} }
} }

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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 { struct FindElements {
collected_set: HashSet<i32> collected_set: HashSet<i32>,
} }
/** /**
* `&self` means the method takes an immutable reference. * `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead. * If you need a mutable reference, change it to `&mut self` instead.
*/ */
impl FindElements { impl FindElements {
fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self { fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {
let mut queue = VecDeque::new(); let mut queue = VecDeque::new();
let mut collected_set = HashSet::new(); let mut collected_set = HashSet::new();
@ -61,9 +59,7 @@ impl FindElements {
}; };
} }
FindElements { FindElements { collected_set }
collected_set
}
} }
fn find(&self, target: i32) -> bool { fn find(&self, target: i32) -> bool {
@ -84,6 +80,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_1261() { fn test_1261() {}
}
} }

View File

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

View File

@ -141,35 +141,42 @@ mod tests {
5 5
); );
assert_eq!(Solution::ladder_length("a".to_owned(), "c".to_owned(), vec![ assert_eq!(
Solution::ladder_length(
"a".to_owned(), "a".to_owned(),
"b".to_owned(), "c".to_owned(),
"c".to_owned() vec!["a".to_owned(), "b".to_owned(), "c".to_owned()]
]), 2); ),
2
);
assert_eq!(Solution::ladder_length("a".to_owned(), "c".to_owned(), vec![ assert_eq!(
"c".to_owned() Solution::ladder_length("a".to_owned(), "c".to_owned(), vec!["c".to_owned()]),
]), 2); 2
);
assert_eq!( assert_eq!(
Solution::ladder_length( Solution::ladder_length(
"hot".to_owned(), "hot".to_owned(),
"dog".to_owned(), "dog".to_owned(),
vec![ vec!["hot".to_owned(), "dot".to_owned(), "dog".to_owned(),]
"hot".to_owned(),
"dot".to_owned(),
"dog".to_owned(),
]
), ),
3 3
); );
assert_eq!(Solution::ladder_length("lost".to_owned(), "cost".to_owned(), vec![ assert_eq!(
Solution::ladder_length(
"lost".to_owned(),
"cost".to_owned(),
vec![
"most".to_owned(), "most".to_owned(),
"fist".to_owned(), "fist".to_owned(),
"lost".to_owned(), "lost".to_owned(),
"cost".to_owned(), "cost".to_owned(),
"fish".to_owned() "fish".to_owned()
]), 2); ]
),
2
);
} }
} }

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::rc::Rc;
impl Solution { impl Solution {
fn dfs_sum(node: &Rc<RefCell<TreeNode>>, last_num: i32, result: &mut i32) { fn dfs_sum(node: &Rc<RefCell<TreeNode>>, last_num: i32, result: &mut i32) {
if node.borrow().left.is_none() && node.borrow().right.is_none() { 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 { pub fn sum_numbers(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut result = 0; let mut result = 0;
@ -50,7 +49,6 @@ impl Solution {
Self::dfs_sum(&root, 0, &mut result); Self::dfs_sum(&root, 0, &mut result);
} }
result result
} }
} }
@ -62,6 +60,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_129() { fn test_129() {}
}
} }

View File

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

View File

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

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -12,7 +11,7 @@ impl Solution {
for i in nums { for i in nums {
b = !a & (b ^ i); b = !a & (b ^ i);
a = !b & ( a ^ i); a = !b & (a ^ i);
} }
b b

View File

@ -3,9 +3,8 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::{rc::Rc, cell::RefCell, collections::HashMap}; use std::{cell::RefCell, collections::HashMap, rc::Rc};
struct Trie { struct Trie {
is_word: bool, is_word: bool,
@ -80,9 +79,21 @@ mod tests {
#[test] #[test]
fn test_139() { fn test_139() {
assert!(Solution::word_break("leetcode".to_owned(), vec_string!("leet", "code"))); assert!(Solution::word_break(
assert!(Solution::word_break("applepenapple".to_owned(), vec_string!("apple", "pen"))); "leetcode".to_owned(),
assert!(!Solution::word_break("catsandog".to_owned(), vec_string!("cats", "cat", "sand", "and", "cat"))); vec_string!("leet", "code")
assert!(Solution::word_break("aaaaaaa".to_owned(), vec_string!("aaa", "aaaa"))); ));
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 {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -19,7 +18,12 @@ impl Solution {
out_map.entry(&path[1]).or_insert(0); 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] #[test]
fn test_1436() { 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 {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::rc::Rc;
impl Solution { impl Solution {
pub fn preorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> { pub fn preorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = Vec::new(); let mut result = Vec::new();
@ -56,7 +56,9 @@ mod tests {
#[test] #[test]
fn test_144() { fn test_144() {
assert_eq!(Solution::preorder_traversal(to_tree( assert_eq!(
vec![Some(1), None, Some(2), Some(3)])), vec![1,2,3]); 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
pub fn busy_student(start_time: Vec<i32>, end_time: Vec<i32>, query_time: i32) -> i32 { 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( let start_pos = start_time.iter().enumerate().filter_map(|(pos, &value)| {
|(pos, &value)| {
if value <= query_time { if value <= query_time {
Some(pos) Some(pos)
} else { } else {
None None
} }
} });
);
let pos = start_pos.filter_map( let pos = start_pos.filter_map(|pos| {
|pos| {
if end_time[pos] >= query_time { if end_time[pos] >= query_time {
Some(pos) Some(pos)
} else { } else {
None None
} }
} });
);
pos.count() as i32 pos.count() as i32
} }

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::rc::Rc;
impl Solution { impl Solution {
pub fn postorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> { pub fn postorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = Vec::new(); let mut result = Vec::new();
@ -65,11 +65,13 @@ mod tests {
#[test] #[test]
fn test_145() { fn test_145() {
assert_eq!(Solution::postorder_traversal( assert_eq!(
to_tree(vec![Some(1), None, Some(2), Some(3)])), Solution::postorder_traversal(to_tree(vec![Some(1), None, Some(2), Some(3)])),
vec![3,2,1]); vec![3, 2, 1]
assert_eq!(Solution::postorder_traversal( );
to_tree(vec![Some(2), None, Some(3), None, Some(1)]) assert_eq!(
), vec![1,3,2]); 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::collections::HashMap; use std::collections::HashMap;
@ -33,10 +32,7 @@ impl Slope {
y /= gcd; y /= gcd;
} }
Self { Self { x, y }
x,
y,
}
} }
fn gcd(a: i32, b: i32) -> i32 { fn gcd(a: i32, b: i32) -> i32 {
@ -62,7 +58,7 @@ impl Solution {
} }
let mut map = HashMap::new(); 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 slope = Slope::new(&points[i], &points[j]);
let entry = map.entry(slope).or_insert(0); 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), "*" => stack.push(first * second),
"/" => stack.push(first / second), "/" => stack.push(first / second),
_ => {}, _ => {}
} }
} }
} }
@ -38,6 +38,6 @@ mod tests {
#[test] #[test]
fn test_150() { 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -36,6 +35,9 @@ mod tests {
#[test] #[test]
fn test_151() { 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -32,6 +31,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_153() { fn test_153() {}
}
} }

View File

@ -3,26 +3,23 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::{cmp::Reverse, collections::BinaryHeap}; use std::{cmp::Reverse, collections::BinaryHeap};
struct MinStack { struct MinStack {
heap : BinaryHeap<Reverse<i32>>, heap: BinaryHeap<Reverse<i32>>,
stack: Vec<i32> stack: Vec<i32>,
} }
/** /**
* `&self` means the method takes an immutable reference. * `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead. * If you need a mutable reference, change it to `&mut self` instead.
*/ */
impl MinStack { impl MinStack {
fn new() -> Self { fn new() -> Self {
MinStack { MinStack {
heap: BinaryHeap::new(), heap: BinaryHeap::new(),
stack: vec![] stack: vec![],
} }
} }
@ -64,6 +61,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_155() { fn test_155() {}
}
} }

View File

@ -53,7 +53,7 @@ impl Solution {
let mid = (left + right) / 2; let mid = (left + right) / 2;
if compare(mid) { if compare(mid) {
return mid as i32 return mid as i32;
} }
if nums[mid] < nums[mid + 1] { if nums[mid] < nums[mid + 1] {
@ -75,8 +75,8 @@ mod tests {
#[test] #[test]
fn test_162() { fn test_162() {
assert_eq!(2, Solution::find_peak_element(vec![1,2,3,1])); 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!(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!(1, Solution::find_peak_element(vec![1, 2]));
} }
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -16,17 +15,14 @@ impl Solution {
if sum == target { if sum == target {
break; break;
} } else if sum < target {
else if sum < target {
i += 1; i += 1;
} } else {
else {
j -= 1; 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] #[test]
fn test_167() { 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
struct Stone { struct Stone {
sum: i32, sum: i32,
alice: i32, alice: i32,
bob: i32 bob: i32,
} }
impl Solution { impl Solution {
pub fn stone_game_vi(alice_values: Vec<i32>, bob_values: Vec<i32>) -> i32 { 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()) .zip(bob_values.iter())
.map(|(a,b)| Stone { .map(|(a, b)| Stone {
sum: *a + *b, sum: *a + *b,
alice: *a, alice: *a,
bob: *b bob: *b,
}) })
.collect(); .collect();
stones.sort_unstable_by(|a, b| b.sum.cmp(&a.sum)); stones.sort_unstable_by(|a, b| b.sum.cmp(&a.sum));
let alice_sum: i32 = stones.iter() let alice_sum: i32 = stones.iter().step_by(2).map(|s| s.alice).sum();
.step_by(2) let bob_sum: i32 = stones.iter().skip(1).step_by(2).map(|s| s.bob).sum();
.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 { if alice_sum > bob_sum {
1 1
@ -53,6 +46,6 @@ mod tests {
#[test] #[test]
fn test_1686() { 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -15,13 +14,12 @@ impl Solution {
sum[index + 1] = sum[index] + *value; 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 i in (0..=n - 2).rev() {
for j in i+1..n { for j in i + 1..n {
dp[i][j] = (sum[j + 1] - sum[i + 1] - dp[i + 1][j]).max( dp[i][j] =
sum[j] - sum[i] - dp[i][j - 1] (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] #[test]
fn test_1690() { 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::collections::VecDeque; use std::collections::VecDeque;
@ -12,7 +11,7 @@ impl Solution {
pub fn max_result(nums: Vec<i32>, k: i32) -> i32 { pub fn max_result(nums: Vec<i32>, k: i32) -> i32 {
let n = nums.len(); let n = nums.len();
let k = k as usize; let k = k as usize;
let mut dp = vec![0;n]; let mut dp = vec![0; n];
let mut queue = VecDeque::new(); let mut queue = VecDeque::new();
dp[0] = nums[0]; dp[0] = nums[0];
@ -50,8 +49,11 @@ mod tests {
#[test] #[test]
fn test_1696() { fn test_1696() {
assert_eq!(Solution::max_result(vec![1,-1,-2,4,-7,3], 2), 7); 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![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, -5, -20, 4, -1, 3, -6, -3], 2),
0
);
} }
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -16,11 +15,7 @@ impl Solution {
candidate = i; candidate = i;
} }
count += if candidate == i { count += if candidate == i { 1 } else { -1 };
1
} else {
-1
};
} }
candidate candidate
@ -35,6 +30,6 @@ mod tests {
#[test] #[test]
fn test_169() { 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -27,6 +26,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_172() { fn test_172() {}
}
} }

View File

@ -5,7 +5,7 @@ pub struct Solution {}
use tokio::time::error::Elapsed; use tokio::time::error::Elapsed;
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::rc::Rc;
struct BSTIterator { 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. * If you need a mutable reference, change it to `&mut self` instead.
*/ */
impl BSTIterator { impl BSTIterator {
fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self { fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {
if root.is_none() { if root.is_none() {
return BSTIterator { return BSTIterator { stack: vec![] };
stack: vec![]
};
} }
let mut stack = vec![]; let mut stack = vec![];
@ -64,10 +61,7 @@ impl BSTIterator {
node = left; node = left;
} }
BSTIterator { stack }
BSTIterator {
stack
}
} }
fn next(&mut self) -> i32 { fn next(&mut self) -> i32 {
@ -112,6 +106,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_173() { fn test_173() {}
}
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -43,6 +42,6 @@ mod tests {
#[test] #[test]
fn test_1793() { 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
pub fn letter_combinations(digits: String) -> Vec<String> { pub fn letter_combinations(digits: String) -> Vec<String> {
let mut result = vec![]; 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) .map(|c| (c.to_digit(10).unwrap() - 2) as usize)
.collect(); .collect();
let mut str = Vec::with_capacity(digits.len()); let mut str = Vec::with_capacity(digits.len());

View File

@ -4,11 +4,11 @@
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::collections::BinaryHeap;
use std::cmp::Reverse; use std::cmp::Reverse;
use std::collections::BinaryHeap;
struct SeatManager { 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. * If you need a mutable reference, change it to `&mut self` instead.
*/ */
impl SeatManager { impl SeatManager {
fn new(n: i32) -> Self { fn new(n: i32) -> Self {
let mut heap = BinaryHeap::with_capacity(n as usize); let mut heap = BinaryHeap::with_capacity(n as usize);
@ -24,9 +23,7 @@ impl SeatManager {
heap.push(Reverse(i)); heap.push(Reverse(i));
} }
Self { Self { seats: heap }
seats: heap
}
} }
fn reserve(&mut self) -> i32 { fn reserve(&mut self) -> i32 {

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -14,9 +13,8 @@ impl Solution {
return -1; return -1;
} }
let max_speed = (*dist.iter().max().unwrap()).max( let max_speed = (*dist.iter().max().unwrap())
((dist[n - 1] as f64) / (hour - (n - 1) as f64)).ceil() as i32 .max(((dist[n - 1] as f64) / (hour - (n - 1) as f64)).ceil() as i32);
);
let check = |v: i32| -> bool { let check = |v: i32| -> bool {
let mut time = 0; let mut time = 0;
@ -58,7 +56,10 @@ mod tests {
#[test] #[test]
fn test_1870() { fn test_1870() {
assert_eq!(-1, Solution::min_speed_on_time(vec![1, 1], 1.0)); 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!(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!(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)); assert_eq!(-1, Solution::min_speed_on_time(vec![1, 3, 2], 1.9));

View File

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

View File

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

View File

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

View File

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

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -12,7 +11,7 @@ impl Solution {
let max_time = max_time as usize; let max_time = max_time as usize;
let max_value = i32::MAX / 2; 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]; dp[0][0] = passing_fees[0];
@ -48,7 +47,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_1928() { fn test_1928() {}
}
} }

View File

@ -5,7 +5,6 @@ use std::convert::TryInto;
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -20,7 +19,9 @@ impl Solution {
let y = 1 << (p - 1); let y = 1 << (p - 1);
dbg!(x, y); 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 { fn fast_power(x: i64, n: i64, m: i64) -> i64 {

View File

@ -3,14 +3,13 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::collections::BinaryHeap; use std::collections::BinaryHeap;
#[derive(PartialEq, Eq)] #[derive(PartialEq, Eq)]
struct Node { struct Node {
node: usize, node: usize,
distance: i64 distance: i64,
} }
impl PartialOrd for Node { impl PartialOrd for Node {
@ -29,7 +28,7 @@ impl Solution {
pub fn count_paths(n: i32, roads: Vec<Vec<i32>>) -> i32 { pub fn count_paths(n: i32, roads: Vec<Vec<i32>>) -> i32 {
let m = 1e9 as i32 + 7; let m = 1e9 as i32 + 7;
let n = n as usize; let n = n as usize;
let mut graph = vec![vec![];n]; let mut graph = vec![vec![]; n];
for road in roads { for road in roads {
let x = road[0] as usize; let x = road[0] as usize;
@ -40,13 +39,16 @@ impl Solution {
graph[y].push((x, t)); graph[y].push((x, t));
} }
let mut distance = vec![i64::MAX;n]; let mut distance = vec![i64::MAX; n];
distance[0] = 0; distance[0] = 0;
let mut ways = vec![0;n]; let mut ways = vec![0; n];
ways[0] = 1; ways[0] = 1;
let mut queue = BinaryHeap::new(); let mut queue = BinaryHeap::new();
queue.push(Node {node: 0, distance: 0}); queue.push(Node {
node: 0,
distance: 0,
});
while !queue.is_empty() { while !queue.is_empty() {
let now = queue.pop().unwrap(); let now = queue.pop().unwrap();
@ -60,7 +62,10 @@ impl Solution {
distance[next.0] = now.distance + next.1; distance[next.0] = now.distance + next.1;
ways[next.0] = ways[now.node]; 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] { } else if now.distance + next.1 == distance[next.0] {
ways[next.0] = (ways[now.node] + ways[next.0]) % m; ways[next.0] = (ways[now.node] + ways[next.0]) % m;
} }
@ -78,7 +83,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_1976() { fn test_1976() {}
}
} }

View File

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

View File

@ -3,13 +3,12 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
pub fn first_day_been_in_all_rooms(next_visit: Vec<i32>) -> i32 { pub fn first_day_been_in_all_rooms(next_visit: Vec<i32>) -> i32 {
let m = 1_000_000_007; 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; dp[0] = 2;
for i in 1..next_visit.len() { for i in 1..next_visit.len() {
@ -34,6 +33,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_1997() { fn test_1997() {}
}
} }

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::rc::Rc;
impl Solution { impl Solution {
pub fn right_side_view(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> { pub fn right_side_view(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = vec![]; let mut result = vec![];
@ -68,6 +68,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_199() { fn test_199() {}
}
} }

View File

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

View File

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

View File

@ -3,17 +3,16 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
pub fn max_consecutive_answers(answer_key: String, k: i32) -> i32 { 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')) 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 n = str.len();
let mut result = 0; let mut result = 0;
@ -21,13 +20,13 @@ impl Solution {
for right in 0..n { for right in 0..n {
sum += match str[right] == c { sum += match str[right] == c {
true => 0, true => 0,
false => 1 false => 1,
}; };
while sum > k { while sum > k {
sum -= match str[left] == c { sum -= match str[left] == c {
true => 0, true => 0,
false => 1 false => 1,
}; };
left += 1; left += 1;
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::collections::HashMap; use std::collections::HashMap;
@ -37,6 +36,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_205() { fn test_205() {}
}
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -13,11 +12,7 @@ impl Solution {
let mut queue = VecDeque::with_capacity(tickets.len()); let mut queue = VecDeque::with_capacity(tickets.len());
for (i, &v) in tickets.iter().enumerate() { for (i, &v) in tickets.iter().enumerate() {
queue.push_back(if i == k { queue.push_back(if i == k { (v, true) } else { (v, false) });
(v, true)
} else {
(v, false)
});
} }
let mut second = 0; let mut second = 0;
@ -48,7 +43,7 @@ mod tests {
#[test] #[test]
fn test_2073() { fn test_2073() {
assert_eq!(6, Solution::time_required_to_buy(vec![2,3,2], 2)); 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!(8, Solution::time_required_to_buy(vec![5, 1, 1, 1], 0));
} }
} }

View File

@ -3,15 +3,14 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::collections::VecDeque; use std::collections::VecDeque;
impl Solution { impl Solution {
pub fn can_finish(num_courses: i32, prerequisites: Vec<Vec<i32>>) -> bool { pub fn can_finish(num_courses: i32, prerequisites: Vec<Vec<i32>>) -> bool {
let num_courses = num_courses as usize; let num_courses = num_courses as usize;
let mut edges = vec![vec![];num_courses]; let mut edges = vec![vec![]; num_courses];
let mut in_degs = vec![0;num_courses]; let mut in_degs = vec![0; num_courses];
for edge in prerequisites { for edge in prerequisites {
edges[edge[1] as usize].push(edge[0] as usize); edges[edge[1] as usize].push(edge[0] as usize);
@ -51,6 +50,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_207() { fn test_207() {}
}
} }

View File

@ -50,9 +50,10 @@ impl Solution {
for i in &words1 { for i in &words1 {
match dict.get(i) { match dict.get(i) {
None => { None => {
dict.insert(i, 0);} dict.insert(i, 0);
}
Some(_) => { Some(_) => {
dict.insert(i ,1); dict.insert(i, 1);
} }
} }
} }
@ -63,14 +64,14 @@ impl Solution {
Some(value) => { Some(value) => {
if *value == 0 { if *value == 0 {
dict.insert(i, 2); dict.insert(i, 2);
} else if *value == 2{ } else if *value == 2 {
dict.insert(i, 1); 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::*; use super::*;
#[test] #[test]
fn test_2085() { fn test_2085() {}
}
} }

View File

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

View File

@ -48,23 +48,21 @@ impl Solution {
for c in s.chars() { for c in s.chars() {
if left.contains(&c) { if left.contains(&c) {
stack.push(c) stack.push(c)
} } else if right.contains(&c) {
else if right.contains(&c) {
let target = match c { let target = match c {
')' => '(', ')' => '(',
']' => '[', ']' => '[',
'}' => '{', '}' => '{',
_ => return false _ => return false,
}; };
if stack.ends_with(&[target]) { if stack.ends_with(&[target]) {
stack.pop(); stack.pop();
} } else {
else { return false;
return false
} }
} else { } else {
return false return false;
} }
} }

View File

@ -3,15 +3,14 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::collections::VecDeque; use std::collections::VecDeque;
impl Solution { impl Solution {
pub fn find_order(num_courses: i32, prerequisites: Vec<Vec<i32>>) -> Vec<i32> { pub fn find_order(num_courses: i32, prerequisites: Vec<Vec<i32>>) -> Vec<i32> {
let num = num_courses as usize; let num = num_courses as usize;
let mut edges = vec![vec![];num]; let mut edges = vec![vec![]; num];
let mut in_degs = vec![0;num]; let mut in_degs = vec![0; num];
for edge in prerequisites { for edge in prerequisites {
let (x, y) = (edge[1] as usize, edge[0] as usize); let (x, y) = (edge[1] as usize, edge[0] as usize);
@ -58,6 +57,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_210() { fn test_210() {}
}
} }

View File

@ -4,7 +4,11 @@
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::{rc::Rc, cell::RefCell, collections::{HashMap, VecDeque}}; use std::{
cell::RefCell,
collections::{HashMap, VecDeque},
rc::Rc,
};
struct TireNode { struct TireNode {
is_word: bool, is_word: bool,
@ -31,7 +35,7 @@ struct WordDictionary {
impl WordDictionary { impl WordDictionary {
fn new() -> Self { fn new() -> Self {
WordDictionary { 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() { for (i, c) in word.chars().enumerate() {
if node.borrow().next.contains_key(&c) { if node.borrow().next.contains_key(&c) {
if i == word.len() - 1 { if i == word.len() - 1 {
node.borrow().next node.borrow().next.get(&c).unwrap().borrow_mut().is_word = true;
.get(&c)
.unwrap()
.borrow_mut().is_word = true;
} }
} else { } else {
if i == word.len() - 1 { 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 { } 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(); let node = queue.pop_front().unwrap();
if i == word.len() - 1 { if i == word.len() - 1 {
if c == '.' && node.borrow().next.iter().any(|(_, n)| { if c == '.' && node.borrow().next.iter().any(|(_, n)| n.borrow().is_word) {
n.borrow().is_word
}) {
return true; return true;
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -31,7 +30,13 @@ mod tests {
#[test] #[test]
fn test_2129() { fn test_2129() {
assert_eq!("Capitalize The Title", Solution::capitalize_title("capiTalIze tHe titLe".to_owned())); assert_eq!(
assert_eq!("First Letter of Each Word", Solution::capitalize_title("First leTTeR of EACH Word".to_owned())); "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 {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::{rc::Rc, cell::RefCell, collections::{HashMap, HashSet}}; use std::{
cell::RefCell,
collections::{HashMap, HashSet},
rc::Rc,
};
#[derive(Debug)] #[derive(Debug)]
struct TrieNode { struct TrieNode {
@ -39,9 +42,13 @@ impl Solution {
} }
} else { } else {
if i == word.len() - 1 { 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 { } 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() 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>, fn dfs(
visited: &mut Vec<Vec<bool>>, x: i32, y: i32) { 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); let (m, n) = (board.len() as i32, board[0].len() as i32);
if x < 0 || x >= m || y < 0 || y >= n { if x < 0 || x >= m || y < 0 || y >= n {
@ -105,7 +119,7 @@ mod tests {
vec!['o', 'a', 'a', 'n'], vec!['o', 'a', 'a', 'n'],
vec!['e', 't', 'a', 'e'], vec!['e', 't', 'a', 'e'],
vec!['i', 'h', 'k', 'r'], vec!['i', 'h', 'k', 'r'],
vec!['i', 'f', 'l', 'v'] vec!['i', 'f', 'l', 'v'],
]; ];
let words = vec_string!("oath", "pea", "eat", "rain"); let words = vec_string!("oath", "pea", "eat", "rain");
@ -120,9 +134,7 @@ mod tests {
#[test] #[test]
fn test_212_2() { fn test_212_2() {
let board = vec![ let board = vec![vec!['a', 'a']];
vec!['a', 'a']
];
let words = vec_string!("aaa"); let words = vec_string!("aaa");
@ -136,7 +148,7 @@ mod tests {
let board = vec![ let board = vec![
vec!['a', 'b', 'c', 'e'], vec!['a', 'b', 'c', 'e'],
vec!['x', 'x', 'c', 'd'], vec!['x', 'x', 'c', 'd'],
vec!['x', 'x', 'b', 'a'] vec!['x', 'x', 'b', 'a'],
]; ];
let words = vec_string!("abc", "abcd"); let words = vec_string!("abc", "abcd");

View File

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

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::cmp::min; use std::cmp::min;
@ -19,8 +18,7 @@ impl Solution {
let mut result = i64::MAX; let mut result = i64::MAX;
for (index, value) in (&beans).iter().enumerate() { for (index, value) in (&beans).iter().enumerate() {
result = min(result, result = min(result, sum - (*value as i64) * (beans.len() - index) as i64);
sum - (*value as i64) * (beans.len() - index) as i64);
} }
result result
@ -35,7 +33,7 @@ mod tests {
#[test] #[test]
fn test_2171() { fn test_2171() {
assert_eq!(Solution::minimum_removal(vec![4,1,6,5]), 4); 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![2, 10, 3, 2]), 7);
} }
} }

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::linked_list::{ListNode, to_list}; use crate::util::linked_list::{to_list, ListNode};
// submission codes start here // submission codes start here
@ -62,7 +62,13 @@ mod tests {
#[test] #[test]
fn test_2181() { 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!(
assert_eq!(to_list(vec![1, 3, 4]), Solution::merge_nodes(to_list(vec![0, 1, 0, 3, 0, 2, 2, 0]))); 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::collections::BTreeMap; use std::collections::BTreeMap;
@ -59,11 +58,13 @@ mod tests {
#[test] #[test]
fn test_2182() { fn test_2182() {
assert_eq!(String::from("zzcccac"), Solution::repeat_limited_string( assert_eq!(
String::from("cczazcc"), 3 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("bbabaa"),
Solution::repeat_limited_string(String::from("aababab"), 2)
);
} }
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -46,7 +45,7 @@ mod tests {
#[test] #[test]
fn test_2187() { 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)); assert_eq!(2, Solution::minimum_time(vec![2], 1));
} }
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::collections::HashMap; use std::collections::HashMap;
@ -13,7 +12,7 @@ impl Solution {
for (i, v) in nums.iter().enumerate() { for (i, v) in nums.iter().enumerate() {
if let Some(last_pos) = map.get_mut(v) { 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(); let distance = distance.abs();
if distance > 0 && distance <= k { if distance > 0 && distance <= k {
@ -21,7 +20,6 @@ impl Solution {
} else { } else {
*last_pos = i as i32; *last_pos = i as i32;
} }
} else { } else {
map.insert(*v, i as i32); map.insert(*v, i as i32);
} }
@ -39,7 +37,10 @@ mod tests {
#[test] #[test]
fn test_219() { fn test_219() {
assert!(Solution::contains_nearby_duplicate(vec![1,2,3,1], 3)); 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, 2, 3],
2
));
} }
} }

View File

@ -5,7 +5,7 @@ pub struct Solution {}
use std::borrow::{Borrow, BorrowMut}; 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 // submission codes start here
@ -26,7 +26,10 @@ use crate::util::linked_list::{ListNode, to_list};
// } // }
// } // }
impl Solution { 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 head = None;
let mut now = &mut head; let mut now = &mut head;
@ -46,8 +49,8 @@ impl Solution {
now = &mut now.insert(b).next 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::*; use super::*;
#[test] #[test]
fn test_21() { fn test_21() {}
}
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -37,7 +36,13 @@ mod tests {
#[test] #[test]
fn test_2207() { fn test_2207() {
assert_eq!(4, Solution::maximum_subsequence_count("abdcdbc".to_owned(), "ac".to_owned())); assert_eq!(
assert_eq!(6, Solution::maximum_subsequence_count("aabb".to_owned(), "ab".to_owned())); 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 {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -40,7 +39,10 @@ mod tests {
#[test] #[test]
fn test_221() { 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']])); assert_eq!(0, Solution::maximal_square(vec![vec!['0']]));
} }
} }

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::rc::Rc;
impl Solution { impl Solution {
pub fn count_nodes(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { pub fn count_nodes(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut result = 0; let mut result = 0;
@ -62,6 +62,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_222() { fn test_222() {}
}
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -12,7 +11,7 @@ impl Solution {
let mut result: i64 = 0; let mut result: i64 = 0;
let mut sign = 1; let mut sign = 1;
let s : Vec<char> = s.chars().collect(); let s: Vec<char> = s.chars().collect();
let mut i = 0; let mut i = 0;

View File

@ -3,25 +3,22 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::collections::VecDeque; use std::collections::VecDeque;
struct MyStack { struct MyStack {
queue: VecDeque<i32> queue: VecDeque<i32>,
} }
/** /**
* `&self` means the method takes an immutable reference. * `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead. * If you need a mutable reference, change it to `&mut self` instead.
*/ */
impl MyStack { impl MyStack {
fn new() -> Self { fn new() -> Self {
return MyStack { return MyStack {
queue: VecDeque::new() queue: VecDeque::new(),
} };
} }
fn push(&mut self, x: i32) { fn push(&mut self, x: i32) {

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::rc::Rc;
impl Solution { impl Solution {
pub fn invert_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> { pub fn invert_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
match root { match root {
None => None, None => None,
Some(root) => { Some(root) => {
let left = Self::invert_tree( let left = Self::invert_tree(root.borrow_mut().left.take());
root.borrow_mut().left.take() let right = Self::invert_tree(root.borrow_mut().right.take());
);
let right = Self::invert_tree(
root.borrow_mut().right.take()
);
root.borrow_mut().left = right; root.borrow_mut().left = right;
root.borrow_mut().right = left; root.borrow_mut().right = left;

View File

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

View File

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

View File

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

View File

@ -3,12 +3,11 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
pub fn distinct_names(ideas: Vec<String>) -> i64 { pub fn distinct_names(ideas: Vec<String>) -> i64 {
use std::collections::{HashSet, HashMap}; use std::collections::{HashMap, HashSet};
let mut map = HashMap::new(); let mut map = HashMap::new();
@ -24,7 +23,8 @@ impl Solution {
for j in i + 1..values.len() { for j in i + 1..values.len() {
let intersect = values[i].intersection(&values[j]).count(); 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] #[test]
fn test_2306() { 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"))); assert_eq!(0, Solution::distinct_names(vec_string!("lack", "back")));
} }
} }

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::rc::Rc;
impl Solution { impl Solution {
fn inorder_iterate(node: &Rc<RefCell<TreeNode>>, count: &mut i32, target: i32) -> Option<i32> { fn inorder_iterate(node: &Rc<RefCell<TreeNode>>, count: &mut i32, target: i32) -> Option<i32> {
if let Some(left) = node.borrow().left.as_ref() { if let Some(left) = node.borrow().left.as_ref() {
@ -53,7 +53,7 @@ impl Solution {
let mut count = 0; let mut count = 0;
if let Some(root) = root { if let Some(root) = root {
return Self::inorder_iterate(&root, &mut count, k).unwrap() return Self::inorder_iterate(&root, &mut count, k).unwrap();
} }
0 0
@ -67,6 +67,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_230() { fn test_230() {}
}
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::collections::HashMap; use std::collections::HashMap;
@ -12,19 +11,20 @@ impl Solution {
let mut prices_map = HashMap::with_capacity(prices.len()); let mut prices_map = HashMap::with_capacity(prices.len());
for price in prices { for price in prices {
prices_map.insert(Solution::hash(price[0] as usize, price[1] as usize), prices_map.insert(
price[2] as i64); Solution::hash(price[0] as usize, price[1] as usize),
price[2] as i64,
);
} }
let (m, n) = (m as usize, n as usize); 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) 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; return x * 1000 + y;
} }
@ -33,20 +33,21 @@ impl Solution {
return dp[x][y]; return dp[x][y];
} }
let mut result = *prices_map.get(&Solution::hash(x, y)) let mut result = *prices_map.get(&Solution::hash(x, y)).unwrap_or_else(|| &0);
.unwrap_or_else(|| &0);
if x > 1 { if x > 1 {
for i in 1..x { for i in 1..x {
result = result.max(Solution::dfs(i, y, dp, prices_map) + result = result.max(
Solution::dfs(x - i, y, dp, prices_map)); Solution::dfs(i, y, dp, prices_map) + Solution::dfs(x - i, y, dp, prices_map),
);
} }
} }
if y > 1 { if y > 1 {
for j in 1..y { for j in 1..y {
result = result.max(Solution::dfs(x, j, dp, prices_map) + result = result.max(
Solution::dfs(x, y - j, dp, prices_map)); Solution::dfs(x, j, dp, prices_map) + Solution::dfs(x, y - j, dp, prices_map),
);
} }
} }
@ -62,6 +63,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_2312() { fn test_2312() {}
}
} }

View File

@ -3,26 +3,23 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
use std::collections::VecDeque; use std::collections::VecDeque;
struct MyQueue { struct MyQueue {
in_stack: VecDeque<i32>, in_stack: VecDeque<i32>,
out_stack: VecDeque<i32> out_stack: VecDeque<i32>,
} }
/** /**
* `&self` means the method takes an immutable reference. * `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead. * If you need a mutable reference, change it to `&mut self` instead.
*/ */
impl MyQueue { impl MyQueue {
fn new() -> Self { fn new() -> Self {
MyQueue { MyQueue {
in_stack: VecDeque::new(), in_stack: VecDeque::new(),
out_stack: VecDeque::new() out_stack: VecDeque::new(),
} }
} }

View File

@ -3,7 +3,6 @@
*/ */
pub struct Solution {} pub struct Solution {}
// submission codes start here // submission codes start here
impl Solution { impl Solution {
@ -36,7 +35,7 @@ impl Solution {
// 最后一个上车的哥们 // 最后一个上车的哥们
let mut down_passenger = if last_passenger == 0 { let mut down_passenger = if last_passenger == 0 {
// 特判一下如果没有哥们可以上车的情况 // 特判一下如果没有哥们可以上车的情况
return buses[n - 1] return buses[n - 1];
} else { } else {
last_passenger - 1 last_passenger - 1
}; };
@ -61,7 +60,6 @@ impl Solution {
result result
}; };
loop { loop {
if result != passengers[down_passenger] { if result != passengers[down_passenger] {
break; break;
@ -86,9 +84,22 @@ mod tests {
#[test] #[test]
fn test_2332() { fn test_2332() {
assert_eq!(16, Solution::latest_time_catch_the_bus(vec![10, 20], vec![2, 17, 18, 19], 2)); assert_eq!(
assert_eq!(20, Solution::latest_time_catch_the_bus(vec![20, 30, 10], vec![19, 13, 26, 4, 25, 11, 21], 2)); 16,
assert_eq!(1, Solution::latest_time_catch_the_bus(vec![3], vec![2,3], 2)); 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], 1));
assert_eq!(1, Solution::latest_time_catch_the_bus(vec![2], vec![2], 2)); 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)); assert_eq!(3, Solution::latest_time_catch_the_bus(vec![3], vec![4], 1));

View File

@ -3,7 +3,7 @@
*/ */
pub struct Solution {} pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree}; use crate::util::tree::{to_tree, TreeNode};
// submission codes start here // 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::cell::RefCell;
use std::rc::Rc;
impl Solution { 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 (root, p, q) = (root?, p?, q?);
let mut ancestor = root; let mut ancestor = root;
loop { 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()) 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()) Rc::clone(&ancestor.borrow().right.as_ref().unwrap())
} else { } else {
break; break;
@ -53,6 +61,5 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_235() { fn test_235() {}
}
} }

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