20241024 finished.

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

View File

@ -6,10 +6,13 @@ update:
build: update
cargo build --release
test:
fmt:
cargo fmt
test: fmt
cargo test
commit:
commit: test
#!/usr/bin/env bash
set -euxo pipefail
time=$(date "+%Y%m%d")
@ -20,4 +23,4 @@ commit:
git push
pull id: build
./target/release/leetcode-rust {{id}}
./target/release/leetcode-rust {{id}}

View File

@ -1,3 +1,3 @@
mod problem1;
mod problem2;
mod problem3;
mod problem3;

View File

@ -12,4 +12,4 @@ impl Solution {
result
}
}
}

View File

@ -1,13 +1,13 @@
pub struct Solution;
use std::collections::BinaryHeap;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution {
pub fn min_operations(nums: Vec<i32>, k: i32) -> i32 {
let mut heap = BinaryHeap::new();
let k = k as i64;
for i in nums {
let i = i as i64;
heap.push(Reverse(i));
@ -23,7 +23,6 @@ impl Solution {
result += 1;
}
result
}
}
}

View File

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

View File

@ -9,7 +9,7 @@ pub struct CodeDefinition {
pub value: String,
pub text: String,
#[serde(rename = "defaultCode")]
pub default_code: String
pub default_code: String,
}
/// LeetCode 单个问题
@ -19,7 +19,7 @@ pub struct Problem {
pub content: String,
pub code_definition: Vec<CodeDefinition>,
pub question_id: u32,
pub return_type: String
pub return_type: String,
}
#[derive(Serialize, Deserialize)]
@ -47,7 +47,7 @@ pub struct StatWithStatus {
#[derive(Serialize, Deserialize)]
pub struct Problems {
pub stat_status_pairs: Vec<StatWithStatus>
pub stat_status_pairs: Vec<StatWithStatus>,
}
const QUESTION_QUERY_STRING: &str = r#"
@ -68,7 +68,7 @@ pub struct Query {
#[serde(rename = "operationName")]
operation_name: String,
variables: serde_json::Value,
query: String
query: String,
}
impl Query {
@ -78,15 +78,15 @@ impl Query {
variables: json!({
"titleSlug": title
}),
query: QUESTION_QUERY_STRING.to_owned()
query: QUESTION_QUERY_STRING.to_owned(),
}
}
}
pub struct Fetcher {
client: reqwest::Client
client: reqwest::Client,
}
pub struct ProblemManager {
pub problem_list: Vec<u32>,
}
}

View File

@ -1,6 +1,6 @@
use std::error::Error;
use super::{Fetcher, Problem, Problems, Query};
use serde_derive::{Deserialize, Serialize};
use super::{Problem, Problems, Query, Fetcher};
use std::error::Error;
const PROBLEMS_URL: &str = "https://leetcode.cn/api/problems/algorithms/";
const GRAPHQL_URL: &str = "https://leetcode.cn/graphql";
@ -8,16 +8,12 @@ const GRAPHQL_URL: &str = "https://leetcode.cn/graphql";
impl Fetcher {
pub fn new() -> Fetcher {
Fetcher {
client: reqwest::Client::new()
client: reqwest::Client::new(),
}
}
pub async fn get_problems(&self) -> Result<Problems, reqwest::Error> {
Ok(reqwest::get(PROBLEMS_URL)
.await?
.json()
.await?
)
Ok(reqwest::get(PROBLEMS_URL).await?.json().await?)
}
pub async fn get_problem(self, question_id: u32) -> Result<Problem, Box<dyn Error>> {
@ -28,19 +24,18 @@ impl Fetcher {
Ok(id) => {
if id == question_id {
if problem.paid_only {
return Err("failed to get paid only problem".into())
return Err("failed to get paid only problem".into());
}
let query = match &problem.stat.question_title_slug {
None => {
Err::<Query, Box<dyn Error>>("failed to get problem title slug".into())
}
Some(value) => {
Ok(Query::new(value.as_str()))
}
None => Err::<Query, Box<dyn Error>>(
"failed to get problem title slug".into(),
),
Some(value) => Ok(Query::new(value.as_str())),
}?;
let response = self.client
let response = self
.client
.post(GRAPHQL_URL)
.json(&query)
.send()
@ -48,20 +43,24 @@ impl Fetcher {
.json::<RawProblem>()
.await?;
let title = problem.stat.question_title.clone()
let title = problem
.stat
.question_title
.clone()
.ok_or::<Box<dyn Error>>("failed to get problem title".into())?;
let title_slug = problem.stat.question_title_slug.clone()
let title_slug = problem
.stat
.question_title_slug
.clone()
.ok_or::<Box<dyn Error>>("failed to get problem title slug".into())?;
let return_type = {
let v = serde_json::from_str::<serde_json::Value>(
&response.data.question.meta_data);
v.and_then(|x| {
return Ok(x.to_string().replace("\"", ""))
})
&response.data.question.meta_data,
);
v.and_then(|x| return Ok(x.to_string().replace("\"", "")))
}?;
let code_definition = serde_json::from_str(
&response.data.question.code_definition
)?;
let code_definition =
serde_json::from_str(&response.data.question.code_definition)?;
return Ok(Problem {
title,
@ -69,8 +68,8 @@ impl Fetcher {
code_definition,
content: response.data.question.content,
question_id: id,
return_type
})
return_type,
});
}
}
Err(_) => {}
@ -101,4 +100,4 @@ struct Question {
sample_test_case: String,
#[serde(rename = "metaData")]
meta_data: String,
}
}

View File

@ -1,6 +1,6 @@
use super::{Problem, ProblemManager};
use regex::Regex;
use std::fs;
use regex::{Regex};
impl ProblemManager {
pub fn scan() -> Result<ProblemManager, Box<dyn std::error::Error>> {
@ -11,45 +11,43 @@ impl ProblemManager {
for i in pattern.captures_iter(&mod_content) {
match i.get(1) {
None => {}
Some(value) => {
match value.as_str().parse::<u32>() {
Ok(id) => {
problems.push(id);
}
Err(_) => {}
Some(value) => match value.as_str().parse::<u32>() {
Ok(id) => {
problems.push(id);
}
}
Err(_) => {}
},
}
}
Ok(ProblemManager {
problem_list: problems
problem_list: problems,
})
}
}
impl Problem {
pub fn get_filename(&self) -> String {
format!("p{}_{}", self.question_id, self.title_slug.replace('-', "_"))
format!(
"p{}_{}",
self.question_id,
self.title_slug.replace('-', "_")
)
}
pub fn get_file_content(&self) -> Result<String, Box<dyn std::error::Error>> {
let template = fs::read_to_string("./template.rs")?;
let code = self.code_definition
.iter()
.find(|x| x.value == "rust");
let code = self.code_definition.iter().find(|x| x.value == "rust");
let code = code.ok_or::<Box<dyn std::error::Error>>(
format!("problem {} doesn't have rust version", self.question_id).into()
format!("problem {} doesn't have rust version", self.question_id).into(),
)?;
let source = template
.replace("__PROBLEM_TITLE__", &self.title)
.replace("__PROBLEM_ID__", self.question_id.to_string().as_str())
.replace(
"__PROBLEM_DEFAULT_CODE__",
&code.default_code)
.replace("__PROBLEM_DEFAULT_CODE__", &code.default_code)
.replace("__EXTRA_USE__", &parse_extra_use(&code.default_code));
Ok(source)
@ -69,4 +67,4 @@ fn parse_extra_use(code: &str) -> String {
extra_use_line.push_str("\nuse crate::util::point::Point;")
}
extra_use_line
}
}

View File

@ -1,6 +1,6 @@
#[macro_use]
pub mod util;
pub mod double_week_125;
pub mod problem;
pub mod week_385;
pub mod week_416;
pub mod double_week_125;

View File

@ -1,7 +1,7 @@
use crate::fetch_problem::{Fetcher, ProblemManager};
use std::fs;
use std::io::Write;
use std::path::Path;
use crate::fetch_problem::{Fetcher, ProblemManager};
mod fetch_problem;
@ -22,12 +22,16 @@ async fn main() {
println!("Try to get problem {}...", id);
let problem = fetcher.get_problem(id).await
let problem = fetcher
.get_problem(id)
.await
.expect(&*format!("Failed to get problem {}.", id));
let file_name = problem.get_filename();
println!("Get problem: {}.", file_name);
let content = problem.get_file_content().expect("Failed to format file content");
let content = problem
.get_file_content()
.expect("Failed to format file content");
write_file(&file_name, &content).expect("Failed to write problem file.");
}
@ -55,4 +59,4 @@ fn write_file(file_name: &String, file_content: &String) -> std::io::Result<()>
.open("./src/problem/mod.rs")?;
write!(mod_file, "\nmod {};", file_name)
}
}

View File

@ -1,15 +1,14 @@
pub struct Solution {}
use std::collections::BinaryHeap;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution {
pub fn nums_game(nums: Vec<i32>) -> Vec<i32> {
let mut result = Vec::with_capacity(nums.len());
let m = 1000000007i64;
let (mut lower, mut upper) =
(BinaryHeap::new(), BinaryHeap::new());
let (mut lower, mut upper) = (BinaryHeap::new(), BinaryHeap::new());
let (mut lower_sum, mut upper_sum) = (0i64, 0i64);
for (index, value) in nums.iter().enumerate() {
@ -41,10 +40,9 @@ impl Solution {
}
if (index + 1) % 2 == 0 {
result.push(((upper_sum - lower_sum) % m) as i32 );
result.push(((upper_sum - lower_sum) % m) as i32);
} else {
result.push(((upper_sum - lower_sum + *lower.peek().unwrap() as i64)
% m) as i32);
result.push(((upper_sum - lower_sum + *lower.peek().unwrap() as i64) % m) as i32);
}
}
@ -58,8 +56,14 @@ mod tests {
#[test]
fn test_lcp24() {
assert_eq!(Solution::nums_game(vec![3,4,5,1,6,7]), vec![0,0,0,5,6,7]);
assert_eq!(Solution::nums_game(vec![1,2,3,4,5]), vec![0,0,0,0,0]);
assert_eq!(Solution::nums_game(vec![471, 626, 848]), vec![0, 154,375]);
assert_eq!(
Solution::nums_game(vec![3, 4, 5, 1, 6, 7]),
vec![0, 0, 0, 5, 6, 7]
);
assert_eq!(
Solution::nums_game(vec![1, 2, 3, 4, 5]),
vec![0, 0, 0, 0, 0]
);
assert_eq!(Solution::nums_game(vec![471, 626, 848]), vec![0, 154, 375]);
}
}

View File

@ -1,7 +1,7 @@
pub struct Solution {}
use std::collections::BinaryHeap;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution {
pub fn magic_tower(nums: Vec<i32>) -> i32 {
@ -41,9 +41,10 @@ mod tests {
#[test]
fn test_lcp30() {
assert_eq!(Solution::magic_tower(
vec![100,100,100,-250,-60,-140,-50,-50,100,150]), 1);
assert_eq!(Solution::magic_tower(
vec![-200,-300,400,0]), -1);
assert_eq!(
Solution::magic_tower(vec![100, 100, 100, -250, -60, -140, -50, -50, 100, 150]),
1
);
assert_eq!(Solution::magic_tower(vec![-200, -300, 400, 0]), -1);
}
}
}

View File

@ -1,275 +1,276 @@
mod p1_two_sum;
mod p9_palindrome_number;
mod p20_valid_parentheses;
mod p2697_lexicographically_smallest_palindrome;
mod p2_add_two_numbers;
mod p3_longest_substring_without_repeating_characters;
mod p162_find_peak_element;
mod p2828_check_if_a_string_is_an_acronym_of_words;
mod p52_n_queens_ii;
mod p912_sort_an_array;
mod p1276_number_of_burgers_with_no_waste_of_ingredients;
mod p6_zigzag_conversion;
mod p7_reverse_integer;
mod p4_median_of_two_sorted_arrays;
mod p743_network_delay_time;
mod p447_number_of_boomerangs;
mod p2085_count_common_words_with_one_occurrence;
mod p2182_construct_string_with_repeat_limit;
mod p83_remove_duplicates_from_sorted_list;
mod p82_remove_duplicates_from_sorted_list_ii;
mod p2719_count_of_integers;
mod p2744_find_maximum_number_of_string_pairs;
mod p2171_removing_minimum_number_of_magic_beans;
mod p2809_minimum_time_to_make_array_sum_at_most_x;
mod p2788_split_strings_by_separator;
mod p410_split_array_largest_sum;
mod p670_maximum_swap;
mod p2765_longest_alternating_subarray;
mod p2865_beautiful_towers_i;
mod p2859_sum_of_values_at_indices_with_k_set_bits;
mod p2846_minimum_edge_weight_equilibrium_queries_in_a_tree;
mod p2861_maximum_number_of_alloys;
mod p365_water_and_jug_problem;
mod p514_freedom_trail;
mod p2808_minimum_seconds_to_equalize_a_circular_array;
mod p2670_find_the_distinct_difference_array;
mod lcp24_nums_game;
mod p1686_stone_game_vi;
mod p1690_stone_game_vii;
mod p292_nim_game;
mod p1696_jump_game_vi;
mod lcp30_magic_tower;
mod p2641_cousins_in_binary_tree_ii;
mod p993_cousins_in_binary_tree;
mod p236_lowest_common_ancestor_of_a_binary_tree;
mod p94_binary_tree_inorder_traversal;
mod p144_binary_tree_preorder_traversal;
mod p145_binary_tree_postorder_traversal;
mod p987_vertical_order_traversal_of_a_binary_tree;
mod p100_same_tree;
mod p101_symmetric_tree;
mod p102_binary_tree_level_order_traversal;
mod p107_binary_tree_level_order_traversal_ii;
mod p103_binary_tree_zigzag_level_order_traversal;
mod p104_maximum_depth_of_binary_tree;
mod p105_construct_binary_tree_from_preorder_and_inorder_traversal;
mod p106_construct_binary_tree_from_inorder_and_postorder_traversal;
mod p235_lowest_common_ancestor_of_a_binary_search_tree;
mod p2583_kth_largest_sum_in_a_binary_tree;
mod p2476_closest_nodes_queries_in_a_binary_search_tree;
mod p938_range_sum_of_bst;
mod p889_construct_binary_tree_from_preorder_and_postorder_traversal;
mod p2867_count_valid_paths_in_a_tree;
mod p2673_make_costs_of_paths_equal_in_a_binary_tree;
mod p2581_count_number_of_possible_root_nodes;
mod p2369_check_if_there_is_a_valid_partition_for_the_array;
mod p2368_reachable_nodes_with_restrictions;
mod p225_implement_stack_using_queues;
mod p232_implement_queue_using_stacks;
mod p1976_number_of_ways_to_arrive_at_destination;
mod p2917_find_the_k_or_of_an_array;
mod p2575_find_the_divisibility_array_of_a_string;
mod p2834_find_the_minimum_possible_sum_of_a_beautiful_array;
mod p2386_find_the_k_sum_of_an_array;
mod p299_bulls_and_cows;
mod p2129_capitalize_the_title;
mod p1261_find_elements_in_a_contaminated_binary_tree;
mod p2864_maximum_odd_binary_number;
mod p2789_largest_element_in_an_array_after_merge_operations;
mod p2312_selling_pieces_of_wood;
mod p2684_maximum_number_of_moves_in_a_grid;
mod p310_minimum_height_trees;
mod p303_range_sum_query_immutable;
mod p1793_maximum_score_of_a_good_subarray;
mod p1969_minimum_non_zero_product_of_the_array_elements;
mod p2671_frequency_tracker;
mod p2617_minimum_number_of_visited_cells_in_a_grid;
mod p2549_count_distinct_numbers_on_board;
mod p322_coin_change;
mod p518_coin_change_ii;
mod p2642_design_graph_with_shortest_path_calculator;
mod p2580_count_ways_to_group_overlapping_ranges;
mod p1997_first_day_where_you_have_been_in_all_the_rooms;
mod p2908_minimum_sum_of_mountain_triplets_i;
mod p2952_minimum_number_of_coins_to_be_added;
mod p331_verify_preorder_serialization_of_a_binary_tree;
mod p88_merge_sorted_array;
mod p26_remove_duplicates_from_sorted_array;
mod p27_remove_element;
mod p80_remove_duplicates_from_sorted_array_ii;
mod p169_majority_element;
mod p189_rotate_array;
mod p107_binary_tree_level_order_traversal_ii;
mod p108_convert_sorted_array_to_binary_search_tree;
mod p112_path_sum;
mod p114_flatten_binary_tree_to_linked_list;
mod p120_triangle;
mod p121_best_time_to_buy_and_sell_stock;
mod p122_best_time_to_buy_and_sell_stock_ii;
mod p55_jump_game;
mod p45_jump_game_ii;
mod p274_h_index;
mod p380_insert_delete_getrandom_o1;
mod p238_product_of_array_except_self;
mod p123_best_time_to_buy_and_sell_stock_iii;
mod p124_binary_tree_maximum_path_sum;
mod p125_valid_palindrome;
mod p1261_find_elements_in_a_contaminated_binary_tree;
mod p1276_number_of_burgers_with_no_waste_of_ingredients;
mod p127_word_ladder;
mod p128_longest_consecutive_sequence;
mod p129_sum_root_to_leaf_numbers;
mod p130_surrounded_regions;
mod p134_gas_station;
mod p135_candy;
mod p42_trapping_rain_water;
mod p58_length_of_last_word;
mod p151_reverse_words_in_a_string;
mod p28_find_the_index_of_the_first_occurrence_in_a_string;
mod p68_text_justification;
mod p125_valid_palindrome;
mod p392_is_subsequence;
mod p167_two_sum_ii_input_array_is_sorted;
mod p209_minimum_size_subarray_sum;
mod p30_substring_with_concatenation_of_all_words;
mod p76_minimum_window_substring;
mod p36_valid_sudoku;
mod p54_spiral_matrix;
mod p48_rotate_image;
mod p73_set_matrix_zeroes;
mod p289_game_of_life;
mod p383_ransom_note;
mod p290_word_pattern;
mod p205_isomorphic_strings;
mod p242_valid_anagram;
mod p49_group_anagrams;
mod p202_happy_number;
mod p219_contains_duplicate_ii;
mod p128_longest_consecutive_sequence;
mod p228_summary_ranges;
mod p56_merge_intervals;
mod p57_insert_interval;
mod p452_minimum_number_of_arrows_to_burst_balloons;
mod p71_simplify_path;
mod p155_min_stack;
mod p150_evaluate_reverse_polish_notation;
mod p224_basic_calculator;
mod p21_merge_two_sorted_lists;
mod p104_maximum_depth_of_binary_tree;
mod p100_same_tree;
mod p226_invert_binary_tree;
mod p101_symmetric_tree;
mod p114_flatten_binary_tree_to_linked_list;
mod p112_path_sum;
mod p129_sum_root_to_leaf_numbers;
mod p124_binary_tree_maximum_path_sum;
mod p173_binary_search_tree_iterator;
mod p222_count_complete_tree_nodes;
mod p199_binary_tree_right_side_view;
mod p637_average_of_levels_in_binary_tree;
mod p530_minimum_absolute_difference_in_bst;
mod p230_kth_smallest_element_in_a_bst;
mod p98_validate_binary_search_tree;
mod p200_number_of_islands;
mod p130_surrounded_regions;
mod p399_evaluate_division;
mod p207_course_schedule;
mod p210_course_schedule_ii;
mod p909_snakes_and_ladders;
mod p433_minimum_genetic_mutation;
mod p127_word_ladder;
mod p208_implement_trie_prefix_tree;
mod p211_design_add_and_search_words_data_structure;
mod p212_word_search_ii;
mod p17_letter_combinations_of_a_phone_number;
mod p77_combinations;
mod p46_permutations;
mod p39_combination_sum;
mod p22_generate_parentheses;
mod p79_word_search;
mod p108_convert_sorted_array_to_binary_search_tree;
mod p53_maximum_subarray;
mod p918_maximum_sum_circular_subarray;
mod p35_search_insert_position;
mod p74_search_a_2d_matrix;
mod p33_search_in_rotated_sorted_array;
mod p34_find_first_and_last_position_of_element_in_sorted_array;
mod p153_find_minimum_in_rotated_sorted_array;
mod p215_kth_largest_element_in_an_array;
mod p502_ipo;
mod p373_find_k_pairs_with_smallest_sums;
mod p295_find_median_from_data_stream;
mod p67_add_binary;
mod p190_reverse_bits;
mod p191_number_of_1_bits;
mod p136_single_number;
mod p137_single_number_ii;
mod p201_bitwise_and_of_numbers_range;
mod p66_plus_one;
mod p172_factorial_trailing_zeroes;
mod p69_sqrtx;
mod p50_powx_n;
mod p149_max_points_on_a_line;
mod p70_climbing_stairs;
mod p198_house_robber;
mod p139_word_break;
mod p300_longest_increasing_subsequence;
mod p120_triangle;
mod p64_minimum_path_sum;
mod p63_unique_paths_ii;
mod p97_interleaving_string;
mod p72_edit_distance;
mod p123_best_time_to_buy_and_sell_stock_iii;
mod p144_binary_tree_preorder_traversal;
mod p145_binary_tree_postorder_traversal;
mod p149_max_points_on_a_line;
mod p150_evaluate_reverse_polish_notation;
mod p151_reverse_words_in_a_string;
mod p153_find_minimum_in_rotated_sorted_array;
mod p155_min_stack;
mod p162_find_peak_element;
mod p167_two_sum_ii_input_array_is_sorted;
mod p1686_stone_game_vi;
mod p1690_stone_game_vii;
mod p1696_jump_game_vi;
mod p169_majority_element;
mod p172_factorial_trailing_zeroes;
mod p173_binary_search_tree_iterator;
mod p1793_maximum_score_of_a_good_subarray;
mod p17_letter_combinations_of_a_phone_number;
mod p188_best_time_to_buy_and_sell_stock_iv;
mod p189_rotate_array;
mod p190_reverse_bits;
mod p191_number_of_1_bits;
mod p1969_minimum_non_zero_product_of_the_array_elements;
mod p1976_number_of_ways_to_arrive_at_destination;
mod p198_house_robber;
mod p1997_first_day_where_you_have_been_in_all_the_rooms;
mod p199_binary_tree_right_side_view;
mod p1_two_sum;
mod p200_number_of_islands;
mod p201_bitwise_and_of_numbers_range;
mod p202_happy_number;
mod p205_isomorphic_strings;
mod p207_course_schedule;
mod p2085_count_common_words_with_one_occurrence;
mod p208_implement_trie_prefix_tree;
mod p209_minimum_size_subarray_sum;
mod p20_valid_parentheses;
mod p210_course_schedule_ii;
mod p211_design_add_and_search_words_data_structure;
mod p2129_capitalize_the_title;
mod p212_word_search_ii;
mod p215_kth_largest_element_in_an_array;
mod p2171_removing_minimum_number_of_magic_beans;
mod p2182_construct_string_with_repeat_limit;
mod p219_contains_duplicate_ii;
mod p21_merge_two_sorted_lists;
mod p221_maximal_square;
mod p222_count_complete_tree_nodes;
mod p224_basic_calculator;
mod p225_implement_stack_using_queues;
mod p226_invert_binary_tree;
mod p228_summary_ranges;
mod p22_generate_parentheses;
mod p230_kth_smallest_element_in_a_bst;
mod p2312_selling_pieces_of_wood;
mod p232_implement_queue_using_stacks;
mod p235_lowest_common_ancestor_of_a_binary_search_tree;
mod p2368_reachable_nodes_with_restrictions;
mod p2369_check_if_there_is_a_valid_partition_for_the_array;
mod p236_lowest_common_ancestor_of_a_binary_tree;
mod p2386_find_the_k_sum_of_an_array;
mod p238_product_of_array_except_self;
mod p242_valid_anagram;
mod p2476_closest_nodes_queries_in_a_binary_search_tree;
mod p2549_count_distinct_numbers_on_board;
mod p2575_find_the_divisibility_array_of_a_string;
mod p2580_count_ways_to_group_overlapping_ranges;
mod p2581_count_number_of_possible_root_nodes;
mod p2583_kth_largest_sum_in_a_binary_tree;
mod p2617_minimum_number_of_visited_cells_in_a_grid;
mod p2641_cousins_in_binary_tree_ii;
mod p2642_design_graph_with_shortest_path_calculator;
mod p2670_find_the_distinct_difference_array;
mod p2671_frequency_tracker;
mod p2673_make_costs_of_paths_equal_in_a_binary_tree;
mod p2684_maximum_number_of_moves_in_a_grid;
mod p2697_lexicographically_smallest_palindrome;
mod p26_remove_duplicates_from_sorted_array;
mod p2719_count_of_integers;
mod p2744_find_maximum_number_of_string_pairs;
mod p274_h_index;
mod p2765_longest_alternating_subarray;
mod p2788_split_strings_by_separator;
mod p2789_largest_element_in_an_array_after_merge_operations;
mod p27_remove_element;
mod p2808_minimum_seconds_to_equalize_a_circular_array;
mod p2809_minimum_time_to_make_array_sum_at_most_x;
mod p2828_check_if_a_string_is_an_acronym_of_words;
mod p2834_find_the_minimum_possible_sum_of_a_beautiful_array;
mod p2846_minimum_edge_weight_equilibrium_queries_in_a_tree;
mod p2859_sum_of_values_at_indices_with_k_set_bits;
mod p2861_maximum_number_of_alloys;
mod p2864_maximum_odd_binary_number;
mod p2865_beautiful_towers_i;
mod p2867_count_valid_paths_in_a_tree;
mod p289_game_of_life;
mod p28_find_the_index_of_the_first_occurrence_in_a_string;
mod p2908_minimum_sum_of_mountain_triplets_i;
mod p290_word_pattern;
mod p2917_find_the_k_or_of_an_array;
mod p292_nim_game;
mod p2952_minimum_number_of_coins_to_be_added;
mod p295_find_median_from_data_stream;
mod p299_bulls_and_cows;
mod p2_add_two_numbers;
mod p300_longest_increasing_subsequence;
mod p303_range_sum_query_immutable;
mod p30_substring_with_concatenation_of_all_words;
mod p310_minimum_height_trees;
mod p3117_minimum_sum_of_values_by_dividing_array;
mod p3137_minimum_number_of_operations_to_make_word_k_periodic;
mod p322_coin_change;
mod p331_verify_preorder_serialization_of_a_binary_tree;
mod p33_search_in_rotated_sorted_array;
mod p34_find_first_and_last_position_of_element_in_sorted_array;
mod p35_search_insert_position;
mod p365_water_and_jug_problem;
mod p36_valid_sudoku;
mod p373_find_k_pairs_with_smallest_sums;
mod p380_insert_delete_getrandom_o1;
mod p383_ransom_note;
mod p392_is_subsequence;
mod p399_evaluate_division;
mod p39_combination_sum;
mod p3_longest_substring_without_repeating_characters;
mod p410_split_array_largest_sum;
mod p42_trapping_rain_water;
mod p433_minimum_genetic_mutation;
mod p447_number_of_boomerangs;
mod p452_minimum_number_of_arrows_to_burst_balloons;
mod p45_jump_game_ii;
mod p46_permutations;
mod p48_rotate_image;
mod p49_group_anagrams;
mod p4_median_of_two_sorted_arrays;
mod p502_ipo;
mod p50_powx_n;
mod p514_freedom_trail;
mod p518_coin_change_ii;
mod p52_n_queens_ii;
mod p530_minimum_absolute_difference_in_bst;
mod p53_maximum_subarray;
mod p54_spiral_matrix;
mod p551_student_attendance_record_i;
mod p55_jump_game;
mod p56_merge_intervals;
mod p57_insert_interval;
mod p58_length_of_last_word;
mod p637_average_of_levels_in_binary_tree;
mod p63_unique_paths_ii;
mod p64_minimum_path_sum;
mod p66_plus_one;
mod p670_maximum_swap;
mod p67_add_binary;
mod p68_text_justification;
mod p69_sqrtx;
mod p6_zigzag_conversion;
mod p70_climbing_stairs;
mod p71_simplify_path;
mod p72_edit_distance;
mod p73_set_matrix_zeroes;
mod p743_network_delay_time;
mod p74_search_a_2d_matrix;
mod p76_minimum_window_substring;
mod p77_combinations;
mod p79_word_search;
mod p7_reverse_integer;
mod p80_remove_duplicates_from_sorted_array_ii;
mod p82_remove_duplicates_from_sorted_list_ii;
mod p83_remove_duplicates_from_sorted_list;
mod p889_construct_binary_tree_from_preorder_and_postorder_traversal;
mod p88_merge_sorted_array;
mod p909_snakes_and_ladders;
mod p912_sort_an_array;
mod p918_maximum_sum_circular_subarray;
mod p938_range_sum_of_bst;
mod p94_binary_tree_inorder_traversal;
mod p97_interleaving_string;
mod p987_vertical_order_traversal_of_a_binary_tree;
mod p98_validate_binary_search_tree;
mod p993_cousins_in_binary_tree;
mod p9_palindrome_number;
mod p552_student_attendance_record_ii;
mod p3154_find_number_of_ways_to_reach_the_k_th_stair;
mod p3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k;
mod p3133_minimum_array_end;
mod p3145_find_products_of_elements_of_big_array;
mod p3146_permutation_difference_between_two_strings;
mod p698_partition_to_k_equal_sum_subsets;
mod p3134_find_the_median_of_the_uniqueness_array;
mod p3144_minimum_substring_partition_of_equal_character_frequency;
mod p3142_check_if_grid_satisfies_conditions;
mod p3153_sum_of_digit_differences_of_all_pairs;
mod p3127_make_a_square_with_the_same_color;
mod p1184_distance_between_bus_stops;
mod p1227_airplane_seat_assignment_probability;
mod p1436_destination_city;
mod p1450_number_of_students_doing_homework_at_a_given_time;
mod p1845_seat_reservation_manager;
mod p1870_minimum_speed_to_arrive_on_time;
mod p1884_egg_drop_with_2_eggs_and_n_floors;
mod p1928_minimum_cost_to_reach_destination_in_time;
mod p2024_maximize_the_confusion_of_an_exam;
mod p2708_maximum_strength_of_a_group;
mod p2860_happy_students;
mod p3174_clear_digits;
mod p3176_find_the_maximum_length_of_a_good_subsequence_i;
mod p3177_find_the_maximum_length_of_a_good_subsequence_ii;
mod p977_squares_of_a_sorted_array;
mod p2073_time_needed_to_buy_tickets;
mod p2181_merge_nodes_in_between_zeros;
mod p2187_minimum_time_to_complete_trips;
mod p2207_maximize_number_of_subsequences_in_a_string;
mod p2286_booking_concert_tickets_in_groups;
mod p2306_naming_a_company;
mod p2332_the_latest_time_to_catch_a_bus;
mod p2374_node_with_highest_edge_score;
mod p2376_count_special_integers;
mod p2390_removing_stars_from_a_string;
mod p2398_maximum_number_of_robots_within_budget;
mod p2414_length_of_the_longest_alphabetical_continuous_substring;
mod p2516_take_k_of_each_character_from_left_and_right;
mod p2535_difference_between_element_sum_and_digit_sum_of_an_array;
mod p2552_count_increasing_quadruplets;
mod p2555_maximize_win_from_two_segments;
mod p2576_find_the_maximum_number_of_marked_indices;
mod p2398_maximum_number_of_robots_within_budget;
mod p2390_removing_stars_from_a_string;
mod p2708_maximum_strength_of_a_group;
mod p2848_points_that_intersect_with_cars;
mod p1184_distance_between_bus_stops;
mod p815_bus_routes;
mod p2332_the_latest_time_to_catch_a_bus;
mod p2414_length_of_the_longest_alphabetical_continuous_substring;
mod p2376_count_special_integers;
mod p2374_node_with_highest_edge_score;
mod p997_find_the_town_judge;
mod p2207_maximize_number_of_subsequences_in_a_string;
mod p2306_naming_a_company;
mod p2535_difference_between_element_sum_and_digit_sum_of_an_array;
mod p2516_take_k_of_each_character_from_left_and_right;
mod p2286_booking_concert_tickets_in_groups;
mod p2073_time_needed_to_buy_tickets;
mod p1845_seat_reservation_manager;
mod p983_minimum_cost_for_tickets;
mod p1870_minimum_speed_to_arrive_on_time;
mod p1928_minimum_cost_to_reach_destination_in_time;
mod p1227_airplane_seat_assignment_probability;
mod p2187_minimum_time_to_complete_trips;
mod p871_minimum_number_of_refueling_stops;
mod p1436_destination_city;
mod p3171_find_subarray_with_bitwise_or_closest_to_k;
mod p2860_happy_students;
mod p3007_maximum_number_that_sum_of_the_prices_is_less_than_or_equal_to_k;
mod p3127_make_a_square_with_the_same_color;
mod p3133_minimum_array_end;
mod p3134_find_the_median_of_the_uniqueness_array;
mod p3142_check_if_grid_satisfies_conditions;
mod p3144_minimum_substring_partition_of_equal_character_frequency;
mod p3145_find_products_of_elements_of_big_array;
mod p3146_permutation_difference_between_two_strings;
mod p3153_sum_of_digit_differences_of_all_pairs;
mod p3154_find_number_of_ways_to_reach_the_k_th_stair;
mod p3158_find_the_xor_of_numbers_which_appear_twice;
mod p3162_find_the_number_of_good_pairs_i;
mod p3164_find_the_number_of_good_pairs_ii;
mod p3158_find_the_xor_of_numbers_which_appear_twice;
mod p1884_egg_drop_with_2_eggs_and_n_floors;
mod p887_super_egg_drop;
mod p3200_maximum_height_of_a_triangle;
mod p3194_minimum_average_of_smallest_and_largest_elements;
mod p3193_count_the_number_of_inversions;
mod p3171_find_subarray_with_bitwise_or_closest_to_k;
mod p3174_clear_digits;
mod p3175_find_the_first_player_to_win_k_games_in_a_row;
mod p3176_find_the_maximum_length_of_a_good_subsequence_i;
mod p3177_find_the_maximum_length_of_a_good_subsequence_ii;
mod p3184_count_pairs_that_form_a_complete_day_i;
mod p3185_count_pairs_that_form_a_complete_day_ii;
mod p3191_minimum_operations_to_make_binary_array_elements_equal_to_one_i;
mod p3192_minimum_operations_to_make_binary_array_elements_equal_to_one_ii;
mod p3193_count_the_number_of_inversions;
mod p3194_minimum_average_of_smallest_and_largest_elements;
mod p3200_maximum_height_of_a_triangle;
mod p552_student_attendance_record_ii;
mod p698_partition_to_k_equal_sum_subsets;
mod p815_bus_routes;
mod p871_minimum_number_of_refueling_stops;
mod p887_super_egg_drop;
mod p908_smallest_range_i;
mod p910_smallest_range_ii;
mod p3184_count_pairs_that_form_a_complete_day_i;
mod p3185_count_pairs_that_form_a_complete_day_ii;
mod p977_squares_of_a_sorted_array;
mod p983_minimum_cost_for_tickets;
mod p997_find_the_town_judge;

View File

@ -3,7 +3,7 @@
*/
pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree};
use crate::util::tree::{to_tree, TreeNode};
// submission codes start here
@ -25,11 +25,14 @@ use crate::util::tree::{TreeNode, to_tree};
// }
// }
// }
use std::rc::Rc;
use std::collections::VecDeque;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
pub fn is_same_tree(p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> bool {
pub fn is_same_tree(
p: Option<Rc<RefCell<TreeNode>>>,
q: Option<Rc<RefCell<TreeNode>>>,
) -> bool {
let mut p_queue = VecDeque::new();
let mut q_queue = VecDeque::new();
@ -66,7 +69,7 @@ impl Solution {
if let Some(p_left) = &p_node.borrow().left {
if let Some(q_left) = &q_node.borrow().left {
p_queue.push_back(Rc::clone(p_left));
q_queue.push_back(Rc::clone(q_left));
q_queue.push_back(Rc::clone(q_left));
};
};
@ -90,6 +93,5 @@ mod tests {
use super::*;
#[test]
fn test_100() {
}
fn test_100() {}
}

View File

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

View File

@ -3,7 +3,7 @@
*/
pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree};
use crate::util::tree::{to_tree, TreeNode};
// submission codes start here
@ -25,9 +25,9 @@ use crate::util::tree::{TreeNode, to_tree};
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
pub fn level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
@ -72,8 +72,17 @@ mod tests {
#[test]
fn test_102() {
assert_eq!(Solution::level_order(
to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)])
), vec![vec![3], vec![9, 20], vec![15, 7]]);
assert_eq!(
Solution::level_order(to_tree(vec![
Some(3),
Some(9),
Some(20),
None,
None,
Some(15),
Some(7)
])),
vec![vec![3], vec![9, 20], vec![15, 7]]
);
}
}

View File

@ -3,7 +3,7 @@
*/
pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree};
use crate::util::tree::{to_tree, TreeNode};
// submission codes start here
@ -25,9 +25,9 @@ use crate::util::tree::{TreeNode, to_tree};
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
pub fn zigzag_level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
let root = if let Some(r) = root {
@ -77,8 +77,17 @@ mod tests {
#[test]
fn test_103() {
assert_eq!(Solution::zigzag_level_order(
to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)])
), vec![vec![3], vec![20, 9], vec![15, 7]]);
assert_eq!(
Solution::zigzag_level_order(to_tree(vec![
Some(3),
Some(9),
Some(20),
None,
None,
Some(15),
Some(7)
])),
vec![vec![3], vec![20, 9], vec![15, 7]]
);
}
}

View File

@ -36,7 +36,7 @@ impl Solution {
if let Some(node) = root {
queue.push_back(node);
}
}
while !queue.is_empty() {
let level = queue.len();

View File

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

View File

@ -3,7 +3,7 @@
*/
pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree};
use crate::util::tree::{to_tree, TreeNode};
// submission codes start here
@ -25,9 +25,9 @@ use crate::util::tree::{TreeNode, to_tree};
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
pub fn level_order_bottom(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> {
@ -73,8 +73,17 @@ mod tests {
#[test]
fn test_107() {
assert_eq!(Solution::level_order_bottom(
to_tree(vec![Some(3), Some(9), Some(20), None, None, Some(15), Some(7)])
), vec![vec![15, 7], vec![9, 20], vec![3]]);
assert_eq!(
Solution::level_order_bottom(to_tree(vec![
Some(3),
Some(9),
Some(20),
None,
None,
Some(15),
Some(7)
])),
vec![vec![15, 7], vec![9, 20], vec![3]]
);
}
}

View File

@ -3,7 +3,7 @@
*/
pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree};
use crate::util::tree::{to_tree, TreeNode};
// submission codes start here
@ -25,35 +25,35 @@ use crate::util::tree::{TreeNode, to_tree};
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn sorted_array_to_bst(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
Some(Self::array_to_bst(&nums[..]))
}
fn array_to_bst(array: &[i32]) -> Rc<RefCell<TreeNode>> {
let length = array.len();
if length == 1 {
return Rc::new(RefCell::new(TreeNode::new(array[0])));
}
let middle = length / 2;
let node = Rc::new(RefCell::new(TreeNode::new(array[middle])));
if middle != 0 {
// 左边
let left = &array[..middle];
node.borrow_mut().left = Some(Self::array_to_bst(left));
}
if middle != length - 1 {
let right = &array[middle + 1..];
node.borrow_mut().right = Some(Self::array_to_bst(right));
}
return node;
}
}
@ -65,6 +65,5 @@ mod tests {
use super::*;
#[test]
fn test_108() {
}
fn test_108() {}
}

View File

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

View File

@ -3,14 +3,13 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn distance_between_bus_stops(distance: Vec<i32>, start: i32, destination: i32) -> i32 {
let (start, destination) = (start as usize, destination as usize);
let n = distance.len();
let mut positive = start;
let mut positive_result = 0;
@ -18,7 +17,7 @@ impl Solution {
positive_result += distance[positive];
positive = (positive + 1) % n;
}
let mut negative = start;
let mut negative_result = 0;
@ -26,7 +25,7 @@ impl Solution {
negative = (negative + n - 1) % n;
negative_result += distance[negative]
}
positive_result.min(negative_result)
}
}
@ -39,8 +38,17 @@ mod tests {
#[test]
fn test_1184() {
assert_eq!(1, Solution::distance_between_bus_stops(vec![1,2,3,4], 0, 1));
assert_eq!(3, Solution::distance_between_bus_stops(vec![1,2,3,4],0, 2));
assert_eq!(4, Solution::distance_between_bus_stops(vec![1,2,3,4],0,3));
assert_eq!(
1,
Solution::distance_between_bus_stops(vec![1, 2, 3, 4], 0, 1)
);
assert_eq!(
3,
Solution::distance_between_bus_stops(vec![1, 2, 3, 4], 0, 2)
);
assert_eq!(
4,
Solution::distance_between_bus_stops(vec![1, 2, 3, 4], 0, 3)
);
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -37,6 +36,9 @@ mod tests {
#[test]
fn test_120() {
assert_eq!(11, Solution::minimum_total(vec![vec![2], vec![3, 4], vec![6, 5, 7], vec![4, 1, 8, 3]]));
assert_eq!(
11,
Solution::minimum_total(vec![vec![2], vec![3, 4], vec![6, 5, 7], vec![4, 1, 8, 3]])
);
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -33,6 +32,6 @@ mod tests {
#[test]
fn test_121() {
assert_eq!(1, Solution::max_profit(vec![1,2]));
assert_eq!(1, Solution::max_profit(vec![1, 2]));
}
}

View File

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

View File

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

View File

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

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -32,7 +31,7 @@ impl Solution {
i += 1;
j -= 1;
}
true
}
}
@ -45,7 +44,9 @@ mod tests {
#[test]
fn test_125() {
assert!(Solution::is_palindrome("A man, a plan, a canal: Panama".to_owned()));
assert!(Solution::is_palindrome(
"A man, a plan, a canal: Panama".to_owned()
));
assert!(!Solution::is_palindrome("0P".to_owned()));
}
}

View File

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

View File

@ -2,36 +2,36 @@
* [1276] Number of Burgers with No Waste of Ingredients
*
* Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows:
*
*
* Jumbo Burger: 4 tomato slices and 1 cheese slice.
* Small Burger: 2 Tomato slices and 1 cheese slice.
*
*
* Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [].
*
* <strong class="example">Example 1:
*
*
* Input: tomatoSlices = 16, cheeseSlices = 7
* Output: [1,6]
* Explantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.
* There will be no remaining ingredients.
*
*
* <strong class="example">Example 2:
*
*
* Input: tomatoSlices = 17, cheeseSlices = 4
* Output: []
* Explantion: There will be no way to use all ingredients to make small and jumbo burgers.
*
*
* <strong class="example">Example 3:
*
*
* Input: tomatoSlices = 4, cheeseSlices = 17
* Output: []
* Explantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.
*
*
*
* Constraints:
*
*
* 0 <= tomatoSlices, cheeseSlices <= 10^7
*
*
*/
pub struct Solution {}
@ -42,15 +42,13 @@ pub struct Solution {}
impl Solution {
pub fn num_of_burgers(tomato_slices: i32, cheese_slices: i32) -> Vec<i32> {
let (mut tomato, mut cheese) = (tomato_slices as f32,
cheese_slices as f32);
let (mut tomato, mut cheese) = (tomato_slices as f32, cheese_slices as f32);
if tomato == 0f32 && cheese == 0f32 {
return vec![0, 0]
return vec![0, 0];
}
if tomato == 0f32 ||
tomato / cheese < 2f32 || tomato / cheese > 4f32 {
return vec![]
if tomato == 0f32 || tomato / cheese < 2f32 || tomato / cheese > 4f32 {
return vec![];
}
let mut big_count = 0;
@ -65,10 +63,10 @@ impl Solution {
}
if tomato * cheese == 0f32 {
return vec![]
return vec![];
}
}
vec![big_count, cheese as i32]
}
}
@ -81,7 +79,7 @@ mod tests {
#[test]
fn test_1276() {
let empty_array : Vec<i32> = Vec::new();
let empty_array: Vec<i32> = Vec::new();
assert_eq!(vec![1, 6], Solution::num_of_burgers(16, 7));
assert_eq!(empty_array, Solution::num_of_burgers(17, 4));
assert_eq!(empty_array, Solution::num_of_burgers(4, 17));

View File

@ -19,7 +19,7 @@ impl Solution {
start = i;
break;
}
}
}
let mut neighbors = vec![HashSet::new(); word_list.len()];
@ -51,44 +51,44 @@ impl Solution {
// 如果开始和结束相同
// 则必然是跳了一步
if start == end {
return 2;
return 2;
}
let mut result = i32::MAX;
// dijkstra算法
let mut distances = vec![i32::MAX; word_list.len()];
let mut flags = vec![false; word_list.len()];
distances[start] = 0;
flags[start] = true;
for &i in &neighbors[start] {
distances[i] = 1;
}
let mut flags = vec![false; word_list.len()];
distances[start] = 0;
flags[start] = true;
for &i in &neighbors[start] {
distances[i] = 1;
}
for _ in 1..word_list.len() {
let mut min = i32::MAX;
let mut next = 0;
for _ in 1..word_list.len() {
let mut min = i32::MAX;
let mut next = 0;
for i in 0..word_list.len() {
if !flags[i] && distances[i] < min {
min = distances[i];
next = i;
}
}
flags[next] = true;
if next == end {
result = result.min(min);
break;
}
for &i in &neighbors[next] {
if !flags[i] && min + 1 < distances[i] {
distances[i] = min + 1;
}
for i in 0..word_list.len() {
if !flags[i] && distances[i] < min {
min = distances[i];
next = i;
}
}
flags[next] = true;
if next == end {
result = result.min(min);
break;
}
for &i in &neighbors[next] {
if !flags[i] && min + 1 < distances[i] {
distances[i] = min + 1;
}
}
}
if result == i32::MAX {
0
} else {
@ -140,36 +140,43 @@ mod tests {
),
5
);
assert_eq!(Solution::ladder_length("a".to_owned(), "c".to_owned(), vec![
"a".to_owned(),
"b".to_owned(),
"c".to_owned()
]), 2);
assert_eq!(Solution::ladder_length("a".to_owned(), "c".to_owned(), vec![
"c".to_owned()
]), 2);
assert_eq!(
Solution::ladder_length(
"a".to_owned(),
"c".to_owned(),
vec!["a".to_owned(), "b".to_owned(), "c".to_owned()]
),
2
);
assert_eq!(
Solution::ladder_length("a".to_owned(), "c".to_owned(), vec!["c".to_owned()]),
2
);
assert_eq!(
Solution::ladder_length(
"hot".to_owned(),
"dog".to_owned(),
vec![
"hot".to_owned(),
"dot".to_owned(),
"dog".to_owned(),
]
vec!["hot".to_owned(), "dot".to_owned(), "dog".to_owned(),]
),
3
);
assert_eq!(Solution::ladder_length("lost".to_owned(), "cost".to_owned(), vec![
"most".to_owned(),
"fist".to_owned(),
"lost".to_owned(),
"cost".to_owned(),
"fish".to_owned()
]), 2);
assert_eq!(
Solution::ladder_length(
"lost".to_owned(),
"cost".to_owned(),
vec![
"most".to_owned(),
"fist".to_owned(),
"lost".to_owned(),
"cost".to_owned(),
"fish".to_owned()
]
),
2
);
}
}

View File

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

View File

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

View File

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

View File

@ -3,18 +3,17 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn single_number(nums: Vec<i32>) -> i32 {
let (mut a, mut b) = (0, 0);
let (mut a, mut b) = (0, 0);
for i in nums {
b = !a & (b ^ i);
a = !b & ( a ^ i);
a = !b & (a ^ i);
}
b
}
}

View File

@ -3,9 +3,8 @@
*/
pub struct Solution {}
// submission codes start here
use std::{rc::Rc, cell::RefCell, collections::HashMap};
use std::{cell::RefCell, collections::HashMap, rc::Rc};
struct Trie {
is_word: bool,
@ -80,9 +79,21 @@ mod tests {
#[test]
fn test_139() {
assert!(Solution::word_break("leetcode".to_owned(), vec_string!("leet", "code")));
assert!(Solution::word_break("applepenapple".to_owned(), vec_string!("apple", "pen")));
assert!(!Solution::word_break("catsandog".to_owned(), vec_string!("cats", "cat", "sand", "and", "cat")));
assert!(Solution::word_break("aaaaaaa".to_owned(), vec_string!("aaa", "aaaa")));
assert!(Solution::word_break(
"leetcode".to_owned(),
vec_string!("leet", "code")
));
assert!(Solution::word_break(
"applepenapple".to_owned(),
vec_string!("apple", "pen")
));
assert!(!Solution::word_break(
"catsandog".to_owned(),
vec_string!("cats", "cat", "sand", "and", "cat")
));
assert!(Solution::word_break(
"aaaaaaa".to_owned(),
vec_string!("aaa", "aaaa")
));
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -19,7 +18,12 @@ impl Solution {
out_map.entry(&path[1]).or_insert(0);
}
out_map.iter().filter(|(_, &v)| v == 0).map(|(k, _)| k.to_string()).next().unwrap()
out_map
.iter()
.filter(|(_, &v)| v == 0)
.map(|(k, _)| k.to_string())
.next()
.unwrap()
}
}
@ -31,6 +35,13 @@ mod tests {
#[test]
fn test_1436() {
assert_eq!("A".to_owned(), Solution::dest_city(vec![vec_string!("B", "C"), vec_string!("D", "B"), vec_string!("C", "A")]));
assert_eq!(
"A".to_owned(),
Solution::dest_city(vec![
vec_string!("B", "C"),
vec_string!("D", "B"),
vec_string!("C", "A")
])
);
}
}

View File

@ -3,7 +3,7 @@
*/
pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree};
use crate::util::tree::{to_tree, TreeNode};
// submission codes start here
@ -25,8 +25,8 @@ use crate::util::tree::{TreeNode, to_tree};
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn preorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = Vec::new();
@ -56,7 +56,9 @@ mod tests {
#[test]
fn test_144() {
assert_eq!(Solution::preorder_traversal(to_tree(
vec![Some(1), None, Some(2), Some(3)])), vec![1,2,3]);
assert_eq!(
Solution::preorder_traversal(to_tree(vec![Some(1), None, Some(2), Some(3)])),
vec![1, 2, 3]
);
}
}

View File

@ -3,30 +3,25 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn busy_student(start_time: Vec<i32>, end_time: Vec<i32>, query_time: i32) -> i32 {
let start_pos = start_time.iter().enumerate().filter_map(
|(pos, &value)| {
if value <= query_time {
Some(pos)
} else {
None
}
let start_pos = start_time.iter().enumerate().filter_map(|(pos, &value)| {
if value <= query_time {
Some(pos)
} else {
None
}
);
});
let pos = start_pos.filter_map(
|pos| {
if end_time[pos] >= query_time {
Some(pos)
} else {
None
}
let pos = start_pos.filter_map(|pos| {
if end_time[pos] >= query_time {
Some(pos)
} else {
None
}
);
});
pos.count() as i32
}

View File

@ -3,7 +3,7 @@
*/
pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree};
use crate::util::tree::{to_tree, TreeNode};
// submission codes start here
@ -25,8 +25,8 @@ use crate::util::tree::{TreeNode, to_tree};
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn postorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = Vec::new();
@ -65,11 +65,13 @@ mod tests {
#[test]
fn test_145() {
assert_eq!(Solution::postorder_traversal(
to_tree(vec![Some(1), None, Some(2), Some(3)])),
vec![3,2,1]);
assert_eq!(Solution::postorder_traversal(
to_tree(vec![Some(2), None, Some(3), None, Some(1)])
), vec![1,3,2]);
assert_eq!(
Solution::postorder_traversal(to_tree(vec![Some(1), None, Some(2), Some(3)])),
vec![3, 2, 1]
);
assert_eq!(
Solution::postorder_traversal(to_tree(vec![Some(2), None, Some(3), None, Some(1)])),
vec![1, 3, 2]
);
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
use std::collections::HashMap;
@ -33,10 +32,7 @@ impl Slope {
y /= gcd;
}
Self {
x,
y,
}
Self { x, y }
}
fn gcd(a: i32, b: i32) -> i32 {
@ -60,20 +56,20 @@ impl Solution {
if result > n - i || result > n / 2 {
break;
}
let mut map = HashMap::new();
for j in i+1..n {
for j in i + 1..n {
let slope = Slope::new(&points[i], &points[j]);
let entry = map.entry(slope).or_insert(0);
*entry += 1;
}
let mut max = 0;
for i in map.values() {
max = max.max(*i);
}
result = result.max(max + 1);
}

View File

@ -21,7 +21,7 @@ impl Solution {
"-" => stack.push(first - second),
"*" => stack.push(first * second),
"/" => stack.push(first / second),
_ => {},
_ => {}
}
}
}
@ -38,6 +38,6 @@ mod tests {
#[test]
fn test_150() {
assert_eq!(9, Solution::eval_rpn(vec_string!["2","1","+","3","*"]));
assert_eq!(9, Solution::eval_rpn(vec_string!["2", "1", "+", "3", "*"]));
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -15,7 +14,7 @@ impl Solution {
words.push(word);
}
}
let length = words.len();
let mut result = String::from(words[length - 1]);
@ -36,6 +35,9 @@ mod tests {
#[test]
fn test_151() {
assert_eq!("blue is sky the".to_owned(), Solution::reverse_words("the sky is blue".to_owned()));
assert_eq!(
"blue is sky the".to_owned(),
Solution::reverse_words("the sky is blue".to_owned())
);
}
}

View File

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

View File

@ -3,46 +3,43 @@
*/
pub struct Solution {}
// submission codes start here
use std::{cmp::Reverse, collections::BinaryHeap};
struct MinStack {
heap : BinaryHeap<Reverse<i32>>,
stack: Vec<i32>
heap: BinaryHeap<Reverse<i32>>,
stack: Vec<i32>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MinStack {
fn new() -> Self {
MinStack {
heap: BinaryHeap::new(),
stack: vec![]
stack: vec![],
}
}
fn push(&mut self, val: i32) {
self.heap.push(Reverse(val));
self.stack.push(val);
}
fn pop(&mut self) {
let n = self.stack.pop().unwrap_or(0);
if !self.stack.contains(&n) {
self.heap.retain(|i| i.0 != n);
}
}
}
fn top(&self) -> i32 {
*self.stack.last().unwrap_or(&0)
}
fn get_min(&self) -> i32 {
self.heap.peek().unwrap_or(&Reverse(0)).0
}
@ -64,6 +61,5 @@ mod tests {
use super::*;
#[test]
fn test_155() {
}
fn test_155() {}
}

View File

@ -7,22 +7,22 @@
* You must write an algorithm that runs in O(log n) time.
*
* <strong class="example">Example 1:
*
*
* Input: nums = [1,2,3,1]
* Output: 2
* Explanation: 3 is a peak element and your function should return the index number 2.
* <strong class="example">Example 2:
*
*
* Input: nums = [1,2,1,3,5,6,4]
* Output: 5
* Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
*
* Constraints:
*
*
* 1 <= nums.length <= 1000
* -2^31 <= nums[i] <= 2^31 - 1
* nums[i] != nums[i + 1] for all valid i.
*
*
*/
pub struct Solution {}
@ -53,7 +53,7 @@ impl Solution {
let mid = (left + right) / 2;
if compare(mid) {
return mid as i32
return mid as i32;
}
if nums[mid] < nums[mid + 1] {
@ -75,8 +75,8 @@ mod tests {
#[test]
fn test_162() {
assert_eq!(2, Solution::find_peak_element(vec![1,2,3,1]));
assert_eq!(5, Solution::find_peak_element(vec![1,2,1,3,5,6,4]));
assert_eq!(1, Solution::find_peak_element(vec![1,2]));
assert_eq!(2, Solution::find_peak_element(vec![1, 2, 3, 1]));
assert_eq!(5, Solution::find_peak_element(vec![1, 2, 1, 3, 5, 6, 4]));
assert_eq!(1, Solution::find_peak_element(vec![1, 2]));
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -16,17 +15,14 @@ impl Solution {
if sum == target {
break;
}
else if sum < target {
} else if sum < target {
i += 1;
}
else {
} else {
j -= 1;
}
}
vec![(i + 1) as i32 , (j + 1) as i32]
vec![(i + 1) as i32, (j + 1) as i32]
}
}
@ -38,6 +34,6 @@ mod tests {
#[test]
fn test_167() {
assert_eq!(vec![1,2], Solution::two_sum(vec![2,7,11,15], 9));
assert_eq!(vec![1, 2], Solution::two_sum(vec![2, 7, 11, 15], 9));
}
}

View File

@ -3,37 +3,30 @@
*/
pub struct Solution {}
// submission codes start here
struct Stone {
sum: i32,
alice: i32,
bob: i32
bob: i32,
}
impl Solution {
pub fn stone_game_vi(alice_values: Vec<i32>, bob_values: Vec<i32>) -> i32 {
let mut stones: Vec<Stone> = alice_values.iter()
let mut stones: Vec<Stone> = alice_values
.iter()
.zip(bob_values.iter())
.map(|(a,b)| Stone {
.map(|(a, b)| Stone {
sum: *a + *b,
alice: *a,
bob: *b
bob: *b,
})
.collect();
stones.sort_unstable_by(|a, b| b.sum.cmp(&a.sum));
let alice_sum: i32 = stones.iter()
.step_by(2)
.map(|s| s.alice)
.sum();
let bob_sum: i32 = stones.iter()
.skip(1)
.step_by(2)
.map(|s| s.bob)
.sum();
let alice_sum: i32 = stones.iter().step_by(2).map(|s| s.alice).sum();
let bob_sum: i32 = stones.iter().skip(1).step_by(2).map(|s| s.bob).sum();
if alice_sum > bob_sum {
1
@ -53,6 +46,6 @@ mod tests {
#[test]
fn test_1686() {
assert_eq!(Solution::stone_game_vi(vec![1,3], vec![2,1]), 1);
assert_eq!(Solution::stone_game_vi(vec![1, 3], vec![2, 1]), 1);
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -15,13 +14,12 @@ impl Solution {
sum[index + 1] = sum[index] + *value;
}
let mut dp = vec![vec![0;n];n];
let mut dp = vec![vec![0; n]; n];
for i in (0..=n-2).rev() {
for j in i+1..n {
dp[i][j] = (sum[j + 1] - sum[i + 1] - dp[i + 1][j]).max(
sum[j] - sum[i] - dp[i][j - 1]
);
for i in (0..=n - 2).rev() {
for j in i + 1..n {
dp[i][j] =
(sum[j + 1] - sum[i + 1] - dp[i + 1][j]).max(sum[j] - sum[i] - dp[i][j - 1]);
}
}
@ -37,6 +35,6 @@ mod tests {
#[test]
fn test_1690() {
assert_eq!(Solution::stone_game_vii(vec![5,3,1,4,2]), 6);
assert_eq!(Solution::stone_game_vii(vec![5, 3, 1, 4, 2]), 6);
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
use std::collections::VecDeque;
@ -12,7 +11,7 @@ impl Solution {
pub fn max_result(nums: Vec<i32>, k: i32) -> i32 {
let n = nums.len();
let k = k as usize;
let mut dp = vec![0;n];
let mut dp = vec![0; n];
let mut queue = VecDeque::new();
dp[0] = nums[0];
@ -50,8 +49,11 @@ mod tests {
#[test]
fn test_1696() {
assert_eq!(Solution::max_result(vec![1,-1,-2,4,-7,3], 2), 7);
assert_eq!(Solution::max_result(vec![10,-5,-2,4,0,3], 3), 17);
assert_eq!(Solution::max_result(vec![1,-5,-20,4,-1,3,-6,-3], 2), 0);
assert_eq!(Solution::max_result(vec![1, -1, -2, 4, -7, 3], 2), 7);
assert_eq!(Solution::max_result(vec![10, -5, -2, 4, 0, 3], 3), 17);
assert_eq!(
Solution::max_result(vec![1, -5, -20, 4, -1, 3, -6, -3], 2),
0
);
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -16,11 +15,7 @@ impl Solution {
candidate = i;
}
count += if candidate == i {
1
} else {
-1
};
count += if candidate == i { 1 } else { -1 };
}
candidate
@ -35,6 +30,6 @@ mod tests {
#[test]
fn test_169() {
assert_eq!(3, Solution::majority_element(vec![3,2,3]));
assert_eq!(3, Solution::majority_element(vec![3, 2, 3]));
}
}

View File

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

View File

@ -5,7 +5,7 @@ pub struct Solution {}
use tokio::time::error::Elapsed;
use crate::util::tree::{TreeNode, to_tree};
use crate::util::tree::{to_tree, TreeNode};
// submission codes start here
@ -28,11 +28,11 @@ use crate::util::tree::{TreeNode, to_tree};
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::rc::Rc;
struct BSTIterator {
stack: Vec<Rc<RefCell<TreeNode>>>
stack: Vec<Rc<RefCell<TreeNode>>>,
}
/**
@ -40,13 +40,10 @@ struct BSTIterator {
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl BSTIterator {
fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {
if root.is_none() {
return BSTIterator {
stack: vec![]
};
}
return BSTIterator { stack: vec![] };
}
let mut stack = vec![];
let root = root.unwrap();
@ -64,16 +61,13 @@ impl BSTIterator {
node = left;
}
BSTIterator {
stack
}
BSTIterator { stack }
}
fn next(&mut self) -> i32 {
let node = self.stack.pop().unwrap();
let val = node.borrow().val;
if let Some(right) = &node.borrow().right {
let mut node = Rc::clone(right);
@ -92,7 +86,7 @@ impl BSTIterator {
val
}
fn has_next(&self) -> bool {
!self.stack.is_empty()
}
@ -112,6 +106,5 @@ mod tests {
use super::*;
#[test]
fn test_173() {
}
fn test_173() {}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -43,6 +42,6 @@ mod tests {
#[test]
fn test_1793() {
assert_eq!(15, Solution::maximum_score(vec![1,4,3,7,4,5], 3));
assert_eq!(15, Solution::maximum_score(vec![1, 4, 3, 7, 4, 5], 3));
}
}

View File

@ -3,17 +3,17 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn letter_combinations(digits: String) -> Vec<String> {
let mut result = vec![];
let digits: Vec<usize> = digits.chars()
let digits: Vec<usize> = digits
.chars()
.map(|c| (c.to_digit(10).unwrap() - 2) as usize)
.collect();
let mut str = Vec::with_capacity(digits.len());
Self::search(&digits, &mut str, &mut result, 0);
result
@ -37,7 +37,7 @@ impl Solution {
}
return;
}
for &c in &map[digits[pos]] {
str.push(c);
Self::search(digits, str, result, pos + 1);

View File

@ -4,11 +4,11 @@
pub struct Solution {}
// submission codes start here
use std::collections::BinaryHeap;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
struct SeatManager {
seats: BinaryHeap<Reverse<i32>>
seats: BinaryHeap<Reverse<i32>>,
}
/**
@ -16,24 +16,21 @@ struct SeatManager {
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl SeatManager {
fn new(n: i32) -> Self {
let mut heap = BinaryHeap::with_capacity(n as usize);
for i in 1..=n {
heap.push(Reverse(i));
}
Self {
seats: heap
}
Self { seats: heap }
}
fn reserve(&mut self) -> i32 {
let head = self.seats.pop();
head.unwrap().0
}
fn unreserve(&mut self, seat_number: i32) {
self.seats.push(Reverse(seat_number));
}
@ -55,7 +52,7 @@ mod tests {
#[test]
fn test_1845() {
let mut manager = SeatManager::new(5);
assert_eq!(1, manager.reserve());
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -39,17 +38,17 @@ impl Solution {
1 << 3,
1 << 2,
1 << 1,
1
1,
];
let mut result = 0;
for i in 0..31 {
if n & ARRAY[i] == ARRAY[i] {
result += 1;
}
}
result
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -12,7 +11,7 @@ impl Solution {
let max_time = max_time as usize;
let max_value = i32::MAX / 2;
let mut dp = vec![vec![max_value;n];max_time + 1];
let mut dp = vec![vec![max_value; n]; max_time + 1];
dp[0][0] = passing_fees[0];
@ -26,7 +25,7 @@ impl Solution {
}
}
}
let mut result = max_value;
for t in 1..=max_time {
@ -38,7 +37,7 @@ impl Solution {
} else {
result
}
}
}
}
// submission codes end
@ -48,7 +47,5 @@ mod tests {
use super::*;
#[test]
fn test_1928() {
}
fn test_1928() {}
}

View File

@ -5,7 +5,6 @@ use std::convert::TryInto;
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -13,14 +12,16 @@ impl Solution {
let p = p as i64;
if p == 1 {
return 1;
}
}
let m = 1e9 as i64 + 7;
let x = Solution::fast_power(2, p, m) - 1;
let y = 1 << (p - 1);
dbg!(x, y);
return (Solution::fast_power(x - 1, y - 1, m) * x % m).try_into().unwrap();
return (Solution::fast_power(x - 1, y - 1, m) * x % m)
.try_into()
.unwrap();
}
fn fast_power(x: i64, n: i64, m: i64) -> i64 {

View File

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

View File

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

View File

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

View File

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

View File

@ -6,29 +6,29 @@
* You can return the answer in any order.
*
* <strong class="example">Example 1:
*
*
* Input: nums = [2,7,11,15], target = 9
* Output: [0,1]
* Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
*
*
* <strong class="example">Example 2:
*
*
* Input: nums = [3,2,4], target = 6
* Output: [1,2]
*
*
* <strong class="example">Example 3:
*
*
* Input: nums = [3,3], target = 6
* Output: [0,1]
*
*
*
* Constraints:
*
*
* 2 <= nums.length <= 10^4
* -10^9 <= nums[i] <= 10^9
* -10^9 <= target <= 10^9
* Only one valid answer exists.
*
*
*
* Follow-up: Can you come up with an algorithm that is less than O(n^2)<font face="monospace"> </font>time complexity?
*/

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -41,7 +40,7 @@ impl Solution {
if grid[i][j] == '1' {
result += 1;
Self::dfs(&mut grid, i as i32, j as i32);
}
}
}
}
@ -56,6 +55,5 @@ mod tests {
use super::*;
#[test]
fn test_200() {
}
fn test_200() {}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -13,7 +12,7 @@ impl Solution {
while left < right {
right = right & (right - 1);
}
right
}
}

View File

@ -3,38 +3,37 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn max_consecutive_answers(answer_key: String, k: i32) -> i32 {
let str : Vec<char> = answer_key.chars().collect();
let str: Vec<char> = answer_key.chars().collect();
Self::max_consecutive_char(&str, k, 'T').max(Self::max_consecutive_char(&str, k, 'F'))
}
fn max_consecutive_char(str: &Vec<char>, k: i32, c : char) -> i32 {
fn max_consecutive_char(str: &Vec<char>, k: i32, c: char) -> i32 {
let n = str.len();
let mut result = 0;
let (mut left, mut sum) = (0, 0);
for right in 0..n {
sum += match str[right] == c {
true => 0,
false => 1
false => 1,
};
while sum > k {
sum -= match str[left] == c {
true => 0,
false => 1
false => 1,
};
left += 1;
}
result = result.max(right - left + 1);
}
result as i32
}
}

View File

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

View File

@ -3,39 +3,34 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn time_required_to_buy(tickets: Vec<i32>, k: i32) -> i32 {
use std::collections::VecDeque;
let k = k as usize;
let mut queue = VecDeque::with_capacity(tickets.len());
for (i, &v) in tickets.iter().enumerate() {
queue.push_back(if i == k {
(v, true)
} else {
(v, false)
});
queue.push_back(if i == k { (v, true) } else { (v, false) });
}
let mut second = 0;
loop {
let head = queue.pop_front().unwrap();
second += 1;
if head.0 == 1 {
// 卖完了
if head.1 {
break;
}
} else {
} else {
queue.push_back((head.0 - 1, head.1));
}
}
second
}
}
@ -48,7 +43,7 @@ mod tests {
#[test]
fn test_2073() {
assert_eq!(6, Solution::time_required_to_buy(vec![2,3,2], 2));
assert_eq!(8, Solution::time_required_to_buy(vec![5,1,1,1], 0));
assert_eq!(6, Solution::time_required_to_buy(vec![2, 3, 2], 2));
assert_eq!(8, Solution::time_required_to_buy(vec![5, 1, 1, 1], 0));
}
}

View File

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

View File

@ -4,7 +4,7 @@
* Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.
*
* <strong class="example">Example 1:
*
*
* Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
* Output: 2
* Explanation:
@ -13,26 +13,26 @@
* - "is" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.
* - "as" appears once in words1, but does not appear in words2. We do not count this string.
* Thus, there are 2 strings that appear exactly once in each of the two arrays.
*
*
* <strong class="example">Example 2:
*
*
* Input: words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]
* Output: 0
* Explanation: There are no strings that appear in each of the two arrays.
*
*
* <strong class="example">Example 3:
*
*
* Input: words1 = ["a","ab"], words2 = ["a","a","a","ab"]
* Output: 1
* Explanation: The only string that appears exactly once in each of the two arrays is "ab".
*
*
*
* Constraints:
*
*
* 1 <= words1.length, words2.length <= 1000
* 1 <= words1[i].length, words2[j].length <= 30
* words1[i] and words2[j] consists only of lowercase English letters.
*
*
*/
pub struct Solution {}
@ -50,9 +50,10 @@ impl Solution {
for i in &words1 {
match dict.get(i) {
None => {
dict.insert(i, 0);}
dict.insert(i, 0);
}
Some(_) => {
dict.insert(i ,1);
dict.insert(i, 1);
}
}
}
@ -63,14 +64,14 @@ impl Solution {
Some(value) => {
if *value == 0 {
dict.insert(i, 2);
} else if *value == 2{
} else if *value == 2 {
dict.insert(i, 1);
}
}
}
}
dict.values().filter(|x| {**x == 2}).count() as i32
dict.values().filter(|x| **x == 2).count() as i32
}
}
@ -81,6 +82,5 @@ mod tests {
use super::*;
#[test]
fn test_2085() {
}
fn test_2085() {}
}

View File

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

View File

@ -10,26 +10,26 @@
* </ol>
*
* <strong class="example">Example 1:
*
*
* Input: s = "()"
* Output: true
*
*
* <strong class="example">Example 2:
*
*
* Input: s = "()[]{}"
* Output: true
*
*
* <strong class="example">Example 3:
*
*
* Input: s = "(]"
* Output: false
*
*
*
* Constraints:
*
*
* 1 <= s.length <= 10^4
* s consists of parentheses only '()[]{}'.
*
*
*/
pub struct Solution {}
@ -48,23 +48,21 @@ impl Solution {
for c in s.chars() {
if left.contains(&c) {
stack.push(c)
}
else if right.contains(&c) {
} else if right.contains(&c) {
let target = match c {
')' => '(',
']' => '[',
'}' => '{',
_ => return false
_ => return false,
};
if stack.ends_with(&[target]) {
stack.pop();
}
else {
return false
} else {
return false;
}
} else {
return false
return false;
}
}

View File

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

View File

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

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -31,7 +30,13 @@ mod tests {
#[test]
fn test_2129() {
assert_eq!("Capitalize The Title", Solution::capitalize_title("capiTalIze tHe titLe".to_owned()));
assert_eq!("First Letter of Each Word", Solution::capitalize_title("First leTTeR of EACH Word".to_owned()));
assert_eq!(
"Capitalize The Title",
Solution::capitalize_title("capiTalIze tHe titLe".to_owned())
);
assert_eq!(
"First Letter of Each Word",
Solution::capitalize_title("First leTTeR of EACH Word".to_owned())
);
}
}

View File

@ -3,9 +3,12 @@
*/
pub struct Solution {}
// submission codes start here
use std::{rc::Rc, cell::RefCell, collections::{HashMap, HashSet}};
use std::{
cell::RefCell,
collections::{HashMap, HashSet},
rc::Rc,
};
#[derive(Debug)]
struct TrieNode {
@ -39,9 +42,13 @@ impl Solution {
}
} else {
if i == word.len() - 1 {
node.borrow_mut().next.insert(c, Rc::new(RefCell::new(TrieNode::new(true, index))));
node.borrow_mut()
.next
.insert(c, Rc::new(RefCell::new(TrieNode::new(true, index))));
} else {
node.borrow_mut().next.insert(c, Rc::new(RefCell::new(TrieNode::new(false, usize::MAX))));
node.borrow_mut()
.next
.insert(c, Rc::new(RefCell::new(TrieNode::new(false, usize::MAX))));
}
};
@ -63,8 +70,15 @@ impl Solution {
result.iter().map(|s| s.to_owned()).collect()
}
fn dfs(board: &Vec<Vec<char>>, node: &Rc<RefCell<TrieNode>>, words: &Vec<String>, result: &mut HashSet<String>,
visited: &mut Vec<Vec<bool>>, x: i32, y: i32) {
fn dfs(
board: &Vec<Vec<char>>,
node: &Rc<RefCell<TrieNode>>,
words: &Vec<String>,
result: &mut HashSet<String>,
visited: &mut Vec<Vec<bool>>,
x: i32,
y: i32,
) {
let (m, n) = (board.len() as i32, board[0].len() as i32);
if x < 0 || x >= m || y < 0 || y >= n {
@ -88,7 +102,7 @@ impl Solution {
Self::dfs(board, next, words, result, visited, x + 1, y);
Self::dfs(board, next, words, result, visited, x, y - 1);
};
visited[x as usize][y as usize] = false;
}
}
@ -105,7 +119,7 @@ mod tests {
vec!['o', 'a', 'a', 'n'],
vec!['e', 't', 'a', 'e'],
vec!['i', 'h', 'k', 'r'],
vec!['i', 'f', 'l', 'v']
vec!['i', 'f', 'l', 'v'],
];
let words = vec_string!("oath", "pea", "eat", "rain");
@ -120,9 +134,7 @@ mod tests {
#[test]
fn test_212_2() {
let board = vec![
vec!['a', 'a']
];
let board = vec![vec!['a', 'a']];
let words = vec_string!("aaa");
@ -130,19 +142,19 @@ mod tests {
assert_eq!(result.len(), 0);
}
#[test]
fn test_212_3() {
let board = vec![
vec!['a', 'b', 'c', 'e'],
vec!['x', 'x', 'c', 'd'],
vec!['x', 'x', 'b', 'a']
vec!['x', 'x', 'b', 'a'],
];
let words = vec_string!("abc", "abcd");
let result = Solution::find_words(board, words);
assert_eq!(result.len(), 2);
assert!(result.contains(&"abc".to_owned()));
assert!(result.contains(&"abcd".to_owned()));

View File

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

View File

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

View File

@ -3,7 +3,7 @@
*/
pub struct Solution {}
use crate::util::linked_list::{ListNode, to_list};
use crate::util::linked_list::{to_list, ListNode};
// submission codes start here
@ -62,7 +62,13 @@ mod tests {
#[test]
fn test_2181() {
assert_eq!(to_list(vec![4, 11]), Solution::merge_nodes(to_list(vec![0, 3, 1, 0, 4, 5, 2, 0])));
assert_eq!(to_list(vec![1, 3, 4]), Solution::merge_nodes(to_list(vec![0, 1, 0, 3, 0, 2, 2, 0])));
assert_eq!(
to_list(vec![4, 11]),
Solution::merge_nodes(to_list(vec![0, 3, 1, 0, 4, 5, 2, 0]))
);
assert_eq!(
to_list(vec![1, 3, 4]),
Solution::merge_nodes(to_list(vec![0, 1, 0, 3, 0, 2, 2, 0]))
);
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
use std::collections::BTreeMap;
@ -59,11 +58,13 @@ mod tests {
#[test]
fn test_2182() {
assert_eq!(String::from("zzcccac"), Solution::repeat_limited_string(
String::from("cczazcc"), 3
));
assert_eq!(String::from("bbabaa"), Solution::repeat_limited_string(
String::from("aababab"), 2
));
assert_eq!(
String::from("zzcccac"),
Solution::repeat_limited_string(String::from("cczazcc"), 3)
);
assert_eq!(
String::from("bbabaa"),
Solution::repeat_limited_string(String::from("aababab"), 2)
);
}
}

View File

@ -3,37 +3,36 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn minimum_time(time: Vec<i32>, total_trips: i32) -> i64 {
let time: Vec<i64> = time.iter().map(|x| *x as i64).collect();
let total_trips = total_trips as i64;
let check = |t: i64| -> bool {
let mut trips = 0;
for &bus in time.iter() {
trips += t / bus;
}
trips >= total_trips
};
let mut left = 0;
let mut right = time[0] * total_trips;
while left < right {
let middle = (right - left) / 2 + left;
if check(middle) {
right = middle;
} else {
} else {
left = middle + 1;
}
}
right
}
}
@ -46,7 +45,7 @@ mod tests {
#[test]
fn test_2187() {
assert_eq!(3, Solution::minimum_time(vec![1,2,3], 5));
assert_eq!(3, Solution::minimum_time(vec![1, 2, 3], 5));
assert_eq!(2, Solution::minimum_time(vec![2], 1));
}
}

View File

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

View File

@ -5,7 +5,7 @@ pub struct Solution {}
use std::borrow::{Borrow, BorrowMut};
use crate::util::linked_list::{ListNode, to_list};
use crate::util::linked_list::{to_list, ListNode};
// submission codes start here
@ -26,7 +26,10 @@ use crate::util::linked_list::{ListNode, to_list};
// }
// }
impl Solution {
pub fn merge_two_lists(list1: Option<Box<ListNode>>, list2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
pub fn merge_two_lists(
list1: Option<Box<ListNode>>,
list2: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
let mut head = None;
let mut now = &mut head;
@ -46,8 +49,8 @@ impl Solution {
now = &mut now.insert(b).next
}
},
(x, y) => break x.or(y)
}
(x, y) => break x.or(y),
}
};
@ -62,6 +65,5 @@ mod tests {
use super::*;
#[test]
fn test_21() {
}
fn test_21() {}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -19,7 +18,7 @@ impl Solution {
result += first_count;
second_count += 1;
}
if c == first {
first_count += 1;
}
@ -37,7 +36,13 @@ mod tests {
#[test]
fn test_2207() {
assert_eq!(4, Solution::maximum_subsequence_count("abdcdbc".to_owned(), "ac".to_owned()));
assert_eq!(6, Solution::maximum_subsequence_count("aabb".to_owned(), "ab".to_owned()));
assert_eq!(
4,
Solution::maximum_subsequence_count("abdcdbc".to_owned(), "ac".to_owned())
);
assert_eq!(
6,
Solution::maximum_subsequence_count("aabb".to_owned(), "ab".to_owned())
);
}
}

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -20,10 +19,10 @@ impl Solution {
if i == 0 || j == 0 {
dp[i][j] = 1;
} else {
} else {
dp[i][j] = dp[i - 1][j - 1].min(dp[i - 1][j]).min(dp[i][j - 1]) + 1;
}
result = result.max(dp[i][j]);
}
}
@ -40,7 +39,10 @@ mod tests {
#[test]
fn test_221() {
assert_eq!(1, Solution::maximal_square(vec![vec!['0', '1'], vec!['1', '0']]));
assert_eq!(
1,
Solution::maximal_square(vec![vec!['0', '1'], vec!['1', '0']])
);
assert_eq!(0, Solution::maximal_square(vec![vec!['0']]));
}
}

View File

@ -3,7 +3,7 @@
*/
pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree};
use crate::util::tree::{to_tree, TreeNode};
// submission codes start here
@ -25,9 +25,9 @@ use crate::util::tree::{TreeNode, to_tree};
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
impl Solution {
pub fn count_nodes(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let mut result = 0;
@ -43,7 +43,7 @@ impl Solution {
let node = queue.pop_front().unwrap();
if let Some(left) = &node.borrow().left {
queue.push_back(Rc::clone(left));
queue.push_back(Rc::clone(left));
};
if let Some(right) = &node.borrow().right {
@ -62,6 +62,5 @@ mod tests {
use super::*;
#[test]
fn test_222() {
}
fn test_222() {}
}

View File

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

View File

@ -3,27 +3,24 @@
*/
pub struct Solution {}
// submission codes start here
use std::collections::VecDeque;
struct MyStack {
queue: VecDeque<i32>
queue: VecDeque<i32>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MyStack {
fn new() -> Self {
return MyStack {
queue: VecDeque::new()
}
queue: VecDeque::new(),
};
}
fn push(&mut self, x: i32) {
let mut new_queue = VecDeque::with_capacity(self.queue.capacity() + 1);
new_queue.push_back(x);
@ -34,15 +31,15 @@ impl MyStack {
self.queue = new_queue;
}
fn pop(&mut self) -> i32 {
self.queue.pop_front().unwrap()
}
fn top(&self) -> i32 {
*self.queue.front().unwrap()
}
fn empty(&self) -> bool {
self.queue.is_empty()
}

View File

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

View File

@ -3,14 +3,13 @@
*/
pub struct Solution {}
// submission codes start here
struct BookMyShow {
row_count: i32,
column_count: i32,
min_tree: Vec<i32>,
sum_tree: Vec<i64>
sum_tree: Vec<i64>,
}
/**
@ -24,81 +23,81 @@ impl BookMyShow {
row_count: n,
column_count: m,
min_tree: vec![0; segement_depth],
sum_tree: vec![0; segement_depth]
sum_tree: vec![0; segement_depth],
}
}
fn modify(&mut self, i: usize, l: i32, r: i32, index: i32, val: i32) {
if l == r {
self.min_tree[i] = val;
self.sum_tree[i] = val as i64;
return;
}
let middle = (l + r) / 2;
if index <= middle {
self.modify(i * 2, l, middle, index, val);
} else {
} else {
self.modify(i * 2 + 1, middle + 1, r, index, val)
}
self.min_tree[i] = self.min_tree[i * 2].min(self.min_tree[i * 2 + 1]);
self.sum_tree[i] = self.sum_tree[i * 2] + self.sum_tree[i * 2 + 1];
}
fn query_min_row(&self, i: usize, l: i32, r: i32, val: i32) -> i32 {
if l == r {
return if self.min_tree[i] > val {
self.row_count
} else {
l
}
} else {
l
};
}
let middle = (l + r) / 2;
if self.min_tree[i * 2] <= val {
self.query_min_row(i * 2, l, middle, val)
} else {
} else {
self.query_min_row(i * 2 + 1, middle + 1, r, val)
}
}
fn query_sum(&self, i: usize, l: i32, r: i32, target_left: i32, target_right: i32) -> i64 {
if target_left <= l && r <= target_right {
return self.sum_tree[i];
}
let middle = (l + r) / 2;
let mut result = 0;
if middle >= target_left {
result += self.query_sum(i * 2, l, middle, target_left, target_right)
}
if middle + 1 <= target_right {
result += self.query_sum(i * 2 + 1, middle + 1, r, target_left, target_right);
}
result
}
fn gather(&mut self, k: i32, max_row: i32) -> Vec<i32> {
let target_row = self.query_min_row(1, 0, self.row_count - 1, self.column_count - k);
if target_row > max_row {
return vec![];
}
let used = self.query_sum(1, 0, self.row_count - 1, target_row, target_row) as i32;
self.modify(1, 0, self.row_count - 1, target_row, used + k);
vec![target_row, used]
}
fn scatter(&mut self, k: i32, max_row: i32) -> bool {
let used = self.query_sum(1, 0, self.row_count - 1, 0, max_row);
if ((max_row + 1) as i64 * self.column_count as i64) - used < k as i64 {
return false;
}
let mut target_row = self.query_min_row(1, 0, self.row_count - 1, self.column_count - 1);
let mut k = k;
loop {
@ -107,12 +106,12 @@ impl BookMyShow {
self.modify(1, 0, self.row_count - 1, target_row, used + k);
break;
}
k -= self.column_count - used;
self.modify(1, 0, self.row_count - 1, target_row, self.column_count);
target_row += 1;
}
true
}
}
@ -133,17 +132,17 @@ mod tests {
#[test]
fn test_2286_1() {
let mut show = BookMyShow::new(2, 5);
assert_eq!(vec![0,0], show.gather(4, 0));
assert_eq!(vec![0, 0], show.gather(4, 0));
assert_eq!(Vec::<i32>::new(), show.gather(2, 0));
assert!(show.scatter(5, 1));
assert!(!show.scatter(5, 1));
}
#[test]
fn test_2286_2() {
let mut show = BookMyShow::new(5, 9);
assert_eq!(Vec::<i32>::new(), show.gather(10, 1));
assert!(show.scatter(3, 3));
assert_eq!(vec![1, 0], show.gather(9, 1));

View File

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

View File

@ -3,7 +3,6 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
@ -11,31 +10,31 @@ impl Solution {
let n = n as usize;
let mut result = vec![];
let mut path = Vec::with_capacity(n * 2);
Self::backtrace(n, 0, &mut path, &mut result);
result
}
fn backtrace(left: usize, right: usize, path: &mut Vec<char>, result: &mut Vec<String>) {
if left == 0 && right == 0 {
let t = path.clone();
result.push(t.iter().collect());
return;
}
if left != 0 {
path.push('(');
Self::backtrace(left - 1, right + 1, path, result);
path.pop();
}
if right != 0 {
path.push(')');
Self::backtrace(left, right - 1, path, result);
path.pop();
}
}
}
}
// submission codes end
@ -45,6 +44,5 @@ mod tests {
use super::*;
#[test]
fn test_22() {
}
fn test_22() {}
}

View File

@ -3,31 +3,31 @@
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn distinct_names(ideas: Vec<String>) -> i64 {
use std::collections::{HashSet, HashMap};
use std::collections::{HashMap, HashSet};
let mut map = HashMap::new();
for idea in ideas.iter() {
let entry = map.entry(&idea[..1]).or_insert(HashSet::new());
entry.insert(&idea[1..]);
}
let mut result = 0;
let values: Vec<HashSet<&str>> = map.into_iter().map(|p| p.1).collect();
for i in 0..values.len() {
for j in i + 1..values.len() {
let intersect = values[i].intersection(&values[j]).count();
result += (values[i].len() - intersect) as i64 * (values[j].len() - intersect) as i64
result +=
(values[i].len() - intersect) as i64 * (values[j].len() - intersect) as i64
}
}
result * 2
}
}
@ -40,7 +40,10 @@ mod tests {
#[test]
fn test_2306() {
assert_eq!(6, Solution::distinct_names(vec_string!("coffee", "donuts", "time", "toffee")));
assert_eq!(
6,
Solution::distinct_names(vec_string!("coffee", "donuts", "time", "toffee"))
);
assert_eq!(0, Solution::distinct_names(vec_string!("lack", "back")));
}
}

View File

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

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