├── .cargo └── config ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── src ├── fetcher.rs ├── lib.rs ├── main.rs ├── problem │ └── mod.rs ├── solution │ ├── mod.rs │ ├── s0001_two_sum.rs │ ├── s0002_add_two_numbers.rs │ ├── s0003_longest_substring_without_repeating_characters.rs │ ├── s0004_median_of_two_sorted_arrays.rs │ ├── s0005_longest_palindromic_substring.rs │ ├── s0006_zigzag_conversion.rs │ ├── s0007_reverse_integer.rs │ ├── s0008_string_to_integer_atoi.rs │ ├── s0009_palindrome_number.rs │ ├── s0010_regular_expression_matching.rs │ ├── s0011_container_with_most_water.rs │ ├── s0012_integer_to_roman.rs │ ├── s0013_roman_to_integer.rs │ ├── s0014_longest_common_prefix.rs │ ├── s0015_3sum.rs │ ├── s0016_3sum_closest.rs │ ├── s0017_letter_combinations_of_a_phone_number.rs │ ├── s0018_4sum.rs │ ├── s0019_remove_nth_node_from_end_of_list.rs │ ├── s0020_valid_parentheses.rs │ ├── s0021_merge_two_sorted_lists.rs │ ├── s0022_generate_parentheses.rs │ ├── s0023_merge_k_sorted_lists.rs │ ├── s0024_swap_nodes_in_pairs.rs │ ├── s0025_reverse_nodes_in_k_group.rs │ ├── s0026_remove_duplicates_from_sorted_array.rs │ ├── s0027_remove_element.rs │ ├── s0028_implement_strstr.rs │ ├── s0029_divide_two_integers.rs │ ├── s0030_substring_with_concatenation_of_all_words.rs │ ├── s0031_next_permutation.rs │ ├── s0032_longest_valid_parentheses.rs │ ├── s0033_search_in_rotated_sorted_array.rs │ ├── s0034_find_first_and_last_position_of_element_in_sorted_array.rs │ ├── s0035_search_insert_position.rs │ ├── s0036_valid_sudoku.rs │ ├── s0037_sudoku_solver.rs │ ├── s0038_count_and_say.rs │ ├── s0039_combination_sum.rs │ ├── s0040_combination_sum_ii.rs │ ├── s0041_first_missing_positive.rs │ ├── s0042_trapping_rain_water.rs │ ├── s0043_multiply_strings.rs │ ├── s0044_wildcard_matching.rs │ ├── s0045_jump_game_ii.rs │ ├── s0046_permutations.rs │ ├── s0047_permutations_ii.rs │ ├── s0048_rotate_image.rs │ ├── s0049_group_anagrams.rs │ ├── s0050_powx_n.rs │ ├── s0051_n_queens.rs │ ├── s0052_n_queens_ii.rs │ ├── s0053_maximum_subarray.rs │ ├── s0054_spiral_matrix.rs │ ├── s0055_jump_game.rs │ ├── s0056_merge_intervals.rs │ ├── s0057_insert_interval.rs │ ├── s0058_length_of_last_word.rs │ ├── s0059_spiral_matrix_ii.rs │ ├── s0060_permutation_sequence.rs │ ├── s0061_rotate_list.rs │ ├── s0062_unique_paths.rs │ ├── s0063_unique_paths_ii.rs │ ├── s0064_minimum_path_sum.rs │ ├── s0065_valid_number.rs │ ├── s0066_plus_one.rs │ ├── s0067_add_binary.rs │ ├── s0068_text_justification.rs │ ├── s0069_sqrtx.rs │ ├── s0070_climbing_stairs.rs │ ├── s0071_simplify_path.rs │ ├── s0072_edit_distance.rs │ ├── s0073_set_matrix_zeroes.rs │ ├── s0074_search_a_2d_matrix.rs │ ├── s0075_sort_colors.rs │ ├── s0076_minimum_window_substring.rs │ ├── s0077_combinations.rs │ ├── s0078_subsets.rs │ ├── s0079_word_search.rs │ ├── s0080_remove_duplicates_from_sorted_array_ii.rs │ ├── s0081_search_in_rotated_sorted_array_ii.rs │ ├── s0082_remove_duplicates_from_sorted_list_ii.rs │ ├── s0083_remove_duplicates_from_sorted_list.rs │ ├── s0084_largest_rectangle_in_histogram.rs │ ├── s0085_maximal_rectangle.rs │ ├── s0086_partition_list.rs │ ├── s0087_scramble_string.rs │ ├── s0088_merge_sorted_array.rs │ ├── s0089_gray_code.rs │ ├── s0090_subsets_ii.rs │ ├── s0091_decode_ways.rs │ ├── s0092_reverse_linked_list_ii.rs │ ├── s0093_restore_ip_addresses.rs │ ├── s0094_binary_tree_inorder_traversal.rs │ ├── s0095_unique_binary_search_trees_ii.rs │ ├── s0096_unique_binary_search_trees.rs │ ├── s0097_interleaving_string.rs │ ├── s0098_validate_binary_search_tree.rs │ ├── s0099_recover_binary_search_tree.rs │ ├── s0100_same_tree.rs │ ├── s0101_symmetric_tree.rs │ ├── s0102_binary_tree_level_order_traversal.rs │ ├── s0103_binary_tree_zigzag_level_order_traversal.rs │ ├── s0104_maximum_depth_of_binary_tree.rs │ ├── s0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs │ ├── s0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs │ ├── s0107_binary_tree_level_order_traversal_ii.rs │ ├── s0108_convert_sorted_array_to_binary_search_tree.rs │ ├── s0109_convert_sorted_list_to_binary_search_tree.rs │ ├── s0110_balanced_binary_tree.rs │ ├── s0111_minimum_depth_of_binary_tree.rs │ ├── s0112_path_sum.rs │ ├── s0113_path_sum_ii.rs │ ├── s0114_flatten_binary_tree_to_linked_list.rs │ ├── s0115_distinct_subsequences.rs │ ├── s0118_pascals_triangle.rs │ ├── s0119_pascals_triangle_ii.rs │ ├── s0120_triangle.rs │ ├── s0121_best_time_to_buy_and_sell_stock.rs │ ├── s0122_best_time_to_buy_and_sell_stock_ii.rs │ ├── s0123_best_time_to_buy_and_sell_stock_iii.rs │ ├── s0124_binary_tree_maximum_path_sum.rs │ ├── s0125_valid_palindrome.rs │ ├── s0126_word_ladder_ii.rs │ ├── s0127_word_ladder.rs │ ├── s0128_longest_consecutive_sequence.rs │ ├── s0129_sum_root_to_leaf_numbers.rs │ ├── s0130_surrounded_regions.rs │ ├── s0131_palindrome_partitioning.rs │ ├── s0132_palindrome_partitioning_ii.rs │ ├── s0134_gas_station.rs │ ├── s0135_candy.rs │ ├── s0136_single_number.rs │ ├── s0137_single_number_ii.rs │ ├── s0139_word_break.rs │ ├── s0140_word_break_ii.rs │ ├── s0143_reorder_list.rs │ ├── s0144_binary_tree_preorder_traversal.rs │ ├── s0145_binary_tree_postorder_traversal.rs │ ├── s0146_lru_cache.rs │ ├── s0147_insertion_sort_list.rs │ ├── s0148_sort_list.rs │ ├── s0149_max_points_on_a_line.rs │ ├── s0150_evaluate_reverse_polish_notation.rs │ ├── s0151_reverse_words_in_a_string.rs │ ├── s0152_maximum_product_subarray.rs │ ├── s0153_find_minimum_in_rotated_sorted_array.rs │ ├── s0154_find_minimum_in_rotated_sorted_array_ii.rs │ ├── s0155_min_stack.rs │ ├── s0162_find_peak_element.rs │ ├── s0164_maximum_gap.rs │ ├── s0165_compare_version_numbers.rs │ ├── s0166_fraction_to_recurring_decimal.rs │ ├── s0167_two_sum_ii_input_array_is_sorted.rs │ ├── s0168_excel_sheet_column_title.rs │ ├── s0169_majority_element.rs │ ├── s0171_excel_sheet_column_number.rs │ ├── s0172_factorial_trailing_zeroes.rs │ ├── s0173_binary_search_tree_iterator.rs │ ├── s0174_dungeon_game.rs │ ├── s0179_largest_number.rs │ ├── s0187_repeated_dna_sequences.rs │ ├── s0188_best_time_to_buy_and_sell_stock_iv.rs │ ├── s0189_rotate_array.rs │ ├── s0198_house_robber.rs │ ├── s0199_binary_tree_right_side_view.rs │ ├── s0200_number_of_islands.rs │ ├── s0201_bitwise_and_of_numbers_range.rs │ ├── s0202_happy_number.rs │ ├── s0203_remove_linked_list_elements.rs │ ├── s0204_count_primes.rs │ ├── s0205_isomorphic_strings.rs │ ├── s0206_reverse_linked_list.rs │ ├── s0207_course_schedule.rs │ ├── s0208_implement_trie_prefix_tree.rs │ ├── s0209_minimum_size_subarray_sum.rs │ ├── s0210_course_schedule_ii.rs │ ├── s0211_add_and_search_word_data_structure_design.rs │ ├── s0212_word_search_ii.rs │ ├── s0213_house_robber_ii.rs │ ├── s0214_shortest_palindrome.rs │ ├── s0215_kth_largest_element_in_an_array.rs │ ├── s0216_combination_sum_iii.rs │ ├── s0217_contains_duplicate.rs │ ├── s0218_the_skyline_problem.rs │ ├── s0219_contains_duplicate_ii.rs │ ├── s0220_contains_duplicate_iii.rs │ ├── s0221_maximal_square.rs │ ├── s0222_count_complete_tree_nodes.rs │ ├── s0223_rectangle_area.rs │ ├── s0224_basic_calculator.rs │ ├── s0225_implement_stack_using_queues.rs │ ├── s0226_invert_binary_tree.rs │ ├── s0227_basic_calculator_ii.rs │ ├── s0228_summary_ranges.rs │ ├── s0229_majority_element_ii.rs │ ├── s0230_kth_smallest_element_in_a_bst.rs │ ├── s0231_power_of_two.rs │ ├── s0232_implement_queue_using_stacks.rs │ ├── s0233_number_of_digit_one.rs │ ├── s0238_product_of_array_except_self.rs │ ├── s0239_sliding_window_maximum.rs │ ├── s0241_different_ways_to_add_parentheses.rs │ ├── s0242_valid_anagram.rs │ ├── s0257_binary_tree_paths.rs │ ├── s0258_add_digits.rs │ ├── s0260_single_number_iii.rs │ ├── s0263_ugly_number.rs │ ├── s0264_ugly_number_ii.rs │ ├── s0268_missing_number.rs │ ├── s0273_integer_to_english_words.rs │ ├── s0274_h_index.rs │ ├── s0275_h_index_ii.rs │ ├── s0279_perfect_squares.rs │ ├── s0282_expression_add_operators.rs │ ├── s0283_move_zeroes.rs │ ├── s0287_find_the_duplicate_number.rs │ ├── s0289_game_of_life.rs │ ├── s0290_word_pattern.rs │ ├── s0292_nim_game.rs │ ├── s0295_find_median_from_data_stream.rs │ ├── s0299_bulls_and_cows.rs │ ├── s0300_longest_increasing_subsequence.rs │ ├── s0301_remove_invalid_parentheses.rs │ ├── s0303_range_sum_query_immutable.rs │ ├── s0304_range_sum_query_2d_immutable.rs │ ├── s0306_additive_number.rs │ ├── s0307_range_sum_query_mutable.rs │ ├── s0309_best_time_to_buy_and_sell_stock_with_cooldown.rs │ ├── s0310_minimum_height_trees.rs │ ├── s0312_burst_balloons.rs │ ├── s0313_super_ugly_number.rs │ ├── s0509_fibonacci_number.rs │ ├── s0704_binary_search.rs │ ├── s0969_pancake_sorting.rs │ ├── s1018_binary_prefix_divisible_by_5.rs │ └── s1046_last_stone_weight.rs └── util │ ├── linked_list.rs │ ├── mod.rs │ ├── point.rs │ ├── testing.rs │ ├── tree.rs │ └── vec_string.rs └── template.rs /.cargo/config: -------------------------------------------------------------------------------- 1 | [build] 2 | rustflags = ["-A", "unused"] 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | .idea/ 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leetcode-rust" 3 | version = "0.1.0" 4 | authors = ["alei "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | reqwest = "0.9.8" 9 | serde = "1.0" 10 | serde_json = "1.0" 11 | serde_derive = "1.0" 12 | rand = "0.6.5" 13 | regex = "1.3.4" 14 | futures = { version = "0.3.3", features = ["thread-pool"] } 15 | surf = "1.0.3" 16 | 17 | [lib] 18 | doctest = false 19 | test = true 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # My Leetcode Solution in Rust 2 | 3 | Run `cargo run {id}` to initialize the template submission file of "question #id". 4 | 5 | Run `cargo test test_{id}` to test the solution for "question #id". 6 | 7 | 对于大部分难度为 Hard 的问题, 会有中文的思路注释 8 | 9 | Working in progress, to do: 10 | 11 | - [ ] auto generation of solution list (when 100 problems solved) 12 | 13 | ## Usage 14 | 15 | * Remove all the solution .rs 16 | * Clean lib.rs file 17 | * Start your leetcode journey in rust by typing `cargo run {question_id}` 18 | 19 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | pub mod util; 3 | 4 | pub mod solution; 5 | pub mod problem; 6 | -------------------------------------------------------------------------------- /src/problem/mod.rs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alisenola/coders-rust/600eedbe0681596f32655b96fc2fd89362f9ffe6/src/problem/mod.rs -------------------------------------------------------------------------------- /src/solution/s0001_two_sum.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [1] Two Sum 3 | * 4 | * Given an array of integers, return indices of the two numbers such that they 5 | * add up to a specific target. 6 | * 7 | * You may assume that each input would have exactly one solution, and you may 8 | * not use the same element twice. 9 | * 10 | * Example: 11 | * 12 | * 13 | * Given nums = [2, 7, 11, 15], target = 9, 14 | * 15 | * Because nums[0] + nums[1] = 2 + 7 = 9, 16 | * return [0, 1]. 17 | * 18 | */ 19 | pub struct Solution {} 20 | 21 | // problem: https://leetcode.com/problems/two-sum/ 22 | // discuss: https://leetcode.com/problems/two-sum/discuss/?currentPage=1&orderBy=most_votes&query= 23 | 24 | // submission codes start here 25 | 26 | use std::collections::HashMap; 27 | impl Solution { 28 | pub fn two_sum(nums: Vec, target: i32) -> Vec { 29 | let mut map = HashMap::with_capacity(nums.len()); 30 | for (index, num) in nums.iter().enumerate() { 31 | match map.get(&(target - num)) { 32 | None => { 33 | map.insert(num, index); 34 | } 35 | Some(sub_index) => return vec![*sub_index as i32, index as i32], 36 | } 37 | } 38 | vec![] 39 | } 40 | } 41 | 42 | // submission codes end 43 | 44 | #[cfg(test)] 45 | mod tests { 46 | use super::*; 47 | 48 | #[test] 49 | fn test_1() { 50 | assert_eq!(vec![0, 1], Solution::two_sum(vec![2, 7, 11, 15], 9)); 51 | assert_eq!(vec![1, 2], Solution::two_sum(vec![3, 2, 4], 6)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/solution/s0003_longest_substring_without_repeating_characters.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [3] Longest Substring Without Repeating Characters 3 | * 4 | * Given a string, find the length of the longest substring without repeating characters. 5 | * 6 | * Example: 7 | * 8 | * Input: "abcabcbb" 9 | * Output: 3 10 | * Explanation: The answer is "abc", with the length of 3. 11 | * 12 | */ 13 | pub struct Solution {} 14 | 15 | // problem: https://leetcode.com/problems/longest-substring-without-repeating-characters/ 16 | // discuss: https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/?currentPage=1&orderBy=most_votes&query= 17 | 18 | // submission codes start here 19 | 20 | impl Solution { 21 | pub fn length_of_longest_substring(s: String) -> i32 { 22 | let seq: Vec = s.chars().collect(); 23 | let len = seq.len(); 24 | let (mut start, mut end, mut max) = (0, 0, 0); 25 | 26 | while end < len { 27 | for idx in start..end { 28 | if seq[end] == seq[idx] { 29 | start = idx + 1; 30 | break; 31 | } 32 | } 33 | let curr = end - start + 1; 34 | if curr > max { 35 | max = curr 36 | } 37 | end += 1 38 | } 39 | max as i32 40 | } 41 | } 42 | 43 | // submission codes end 44 | 45 | #[cfg(test)] 46 | mod tests { 47 | use super::*; 48 | 49 | #[test] 50 | fn test_3() { 51 | assert_eq!( 52 | Solution::length_of_longest_substring("abcabcbb".to_string()), 53 | 3 54 | ); 55 | assert_eq!(Solution::length_of_longest_substring("bbbb".to_string()), 1); 56 | assert_eq!( 57 | Solution::length_of_longest_substring("pwwkew".to_string()), 58 | 3 59 | ); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/solution/s0004_median_of_two_sorted_arrays.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [4] Median of Two Sorted Arrays 3 | * 4 | * There are two sorted arrays nums1 and nums2 of size m and n respectively. 5 | * 6 | * Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 7 | * 8 | * You may assume nums1 and nums2 cannot be both empty. 9 | * 10 | * Example 1: 11 | * 12 | * 13 | * nums1 = [1, 3] 14 | * nums2 = [2] 15 | * 16 | * The median is 2.0 17 | * 18 | * 19 | * Example 2: 20 | * 21 | * 22 | * nums1 = [1, 2] 23 | * nums2 = [3, 4] 24 | * 25 | * The median is (2 + 3)/2 = 2.5 26 | * 27 | * 28 | */ 29 | pub struct Solution {} 30 | 31 | // problem: https://leetcode.com/problems/median-of-two-sorted-arrays/ 32 | // discuss: https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/?currentPage=1&orderBy=most_votes&query= 33 | 34 | // submission codes start here 35 | 36 | // TODO: nth slice 37 | impl Solution { 38 | pub fn find_median_sorted_arrays(nums1: Vec, nums2: Vec) -> f64 { 39 | 1.0 40 | } 41 | } 42 | 43 | // submission codes end 44 | 45 | #[cfg(test)] 46 | mod tests { 47 | use super::*; 48 | 49 | // TODO: implementation 50 | #[test] 51 | #[ignore] 52 | fn test_4() { 53 | assert_eq!( 54 | Solution::find_median_sorted_arrays(vec![1, 3], vec![2]), 55 | 2.0 56 | ); 57 | assert_eq!( 58 | Solution::find_median_sorted_arrays(vec![1, 2], vec![3, 4]), 59 | 2.5 60 | ); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/solution/s0007_reverse_integer.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [7] Reverse Integer 3 | * 4 | * Given a 32-bit signed integer, reverse digits of an integer. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: 123 10 | * Output: 321 11 | * 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: -123 17 | * Output: -321 18 | * 19 | * 20 | * Example 3: 21 | * 22 | * 23 | * Input: 120 24 | * Output: 21 25 | * 26 | * 27 | * Note:
28 | * Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31, 2^31 - 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 29 | * 30 | */ 31 | pub struct Solution {} 32 | 33 | // problem: https://leetcode.com/problems/reverse-integer/ 34 | // discuss: https://leetcode.com/problems/reverse-integer/discuss/?currentPage=1&orderBy=most_votes&query= 35 | 36 | // submission codes start here 37 | impl Solution { 38 | pub fn reverse(x: i32) -> i32 { 39 | let mut input: i64 = x as i64; 40 | let mut result: i64 = 0; 41 | let mut digit: i64 = 0; 42 | let base: i64 = 2; 43 | let upper_bound: i64 = base.pow(31) - 1; 44 | let lower_bound: i64 = -base.pow(31); 45 | while input != 0 { 46 | digit = input % 10; 47 | result = result * 10 + digit; 48 | input = input / 10; 49 | } 50 | if result > upper_bound || result < lower_bound { 51 | return 0; 52 | } 53 | result as i32 54 | } 55 | } 56 | 57 | // submission codes end 58 | 59 | #[cfg(test)] 60 | mod tests { 61 | use super::*; 62 | 63 | #[test] 64 | fn test_7() { 65 | assert_eq!(Solution::reverse(123), 321); 66 | assert_eq!(Solution::reverse(-123), -321); 67 | assert_eq!(Solution::reverse(0), 0); 68 | assert_eq!(Solution::reverse(-123000), -321); 69 | let base: i64 = 2; 70 | assert_eq!(Solution::reverse((base.pow(31) - 1) as i32), 0); 71 | assert_eq!(Solution::reverse((-base.pow(31)) as i32), 0); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/solution/s0010_regular_expression_matching.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [10] Regular Expression Matching 3 | * 4 | * Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. 5 | * 6 | * 7 | * '.' Matches any single character. 8 | * '*' Matches zero or more of the preceding element. 9 | * 10 | * 11 | * The matching should cover the entire input string (not partial). 12 | * 13 | * Note: 14 | * 15 | * 16 | * s could be empty and contains only lowercase letters a-z. 17 | * p could be empty and contains only lowercase letters a-z, and characters like . or *. 18 | * 19 | * 20 | * Example 1: 21 | * 22 | * 23 | * Input: 24 | * s = "aa" 25 | * p = "a" 26 | * Output: false 27 | * Explanation: "a" does not match the entire string "aa". 28 | * 29 | * 30 | * Example 2: 31 | * 32 | * 33 | * Input: 34 | * s = "aa" 35 | * p = "a*" 36 | * Output: true 37 | * Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". 38 | * 39 | * 40 | * Example 3: 41 | * 42 | * 43 | * Input: 44 | * s = "ab" 45 | * p = ".*" 46 | * Output: true 47 | * Explanation: ".*" means "zero or more (*) of any character (.)". 48 | * 49 | * 50 | * Example 4: 51 | * 52 | * 53 | * Input: 54 | * s = "aab" 55 | * p = "c*a*b" 56 | * Output: true 57 | * Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab". 58 | * 59 | * 60 | * Example 5: 61 | * 62 | * 63 | * Input: 64 | * s = "mississippi" 65 | * p = "mis*is*p*." 66 | * Output: false 67 | * 68 | * 69 | */ 70 | pub struct Solution {} 71 | 72 | // problem: https://leetcode.com/problems/regular-expression-matching/ 73 | // discuss: https://leetcode.com/problems/regular-expression-matching/discuss/?currentPage=1&orderBy=most_votes&query= 74 | 75 | // submission codes start here 76 | 77 | // TODO: NFA 78 | impl Solution { 79 | pub fn is_match(s: String, p: String) -> bool { 80 | false 81 | } 82 | } 83 | 84 | // submission codes end 85 | 86 | #[cfg(test)] 87 | mod tests { 88 | use super::*; 89 | 90 | #[test] 91 | fn test_10() {} 92 | } 93 | -------------------------------------------------------------------------------- /src/solution/s0019_remove_nth_node_from_end_of_list.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [19] Remove Nth Node From End of List 3 | * 4 | * Given a linked list, remove the n-th node from the end of list and return its head. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Given linked list: 1->2->3->4->5, and n = 2. 10 | * 11 | * After removing the second node from the end, the linked list becomes 1->2->3->5. 12 | * 13 | * 14 | * Note: 15 | * 16 | * Given n will always be valid. 17 | * 18 | * Follow up: 19 | * 20 | * Could you do this in one pass? 21 | * 22 | */ 23 | pub struct Solution {} 24 | use crate::util::linked_list::{to_list, ListNode}; 25 | 26 | // problem: https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 27 | // discuss: https://leetcode.com/problems/remove-nth-node-from-end-of-list/discuss/?currentPage=1&orderBy=most_votes&query= 28 | 29 | // submission codes start here 30 | 31 | // one pass (two pointer runner pattern) cannot make borrow checker happy 32 | // but two pass don't takes longer time 33 | impl Solution { 34 | pub fn remove_nth_from_end(head: Option>, n: i32) -> Option> { 35 | let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head })); 36 | let mut len = 0; 37 | { 38 | let mut p = dummy_head.as_ref(); 39 | while p.unwrap().next.is_some() { 40 | len += 1; 41 | p = p.unwrap().next.as_ref(); 42 | } 43 | } 44 | let idx = len - n; 45 | { 46 | let mut p = dummy_head.as_mut(); 47 | for _ in 0..(idx) { 48 | p = p.unwrap().next.as_mut(); 49 | } 50 | let next = p.as_mut().unwrap().next.as_mut().unwrap().next.take(); 51 | p.as_mut().unwrap().next = next; 52 | } 53 | dummy_head.unwrap().next 54 | } 55 | } 56 | 57 | // submission codes end 58 | 59 | #[cfg(test)] 60 | mod tests { 61 | use super::*; 62 | 63 | #[test] 64 | fn test_19() { 65 | assert_eq!( 66 | Solution::remove_nth_from_end(to_list(vec![1, 2, 3, 4, 5]), 2), 67 | to_list(vec![1, 2, 3, 5]) 68 | ); 69 | assert_eq!(Solution::remove_nth_from_end(to_list(vec![1]), 1), None); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/solution/s0020_valid_parentheses.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [20] Valid Parentheses 3 | * 4 | * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 5 | * 6 | * An input string is valid if: 7 | * 8 | *
    9 | * Open brackets must be closed by the same type of brackets. 10 | * Open brackets must be closed in the correct order. 11 | *
12 | * 13 | * Note that an empty string is also considered valid. 14 | * 15 | * Example 1: 16 | * 17 | * 18 | * Input: "()" 19 | * Output: true 20 | * 21 | * 22 | * Example 2: 23 | * 24 | * 25 | * Input: "()[]{}" 26 | * Output: true 27 | * 28 | * 29 | * Example 3: 30 | * 31 | * 32 | * Input: "(]" 33 | * Output: false 34 | * 35 | * 36 | * Example 4: 37 | * 38 | * 39 | * Input: "([)]" 40 | * Output: false 41 | * 42 | * 43 | * Example 5: 44 | * 45 | * 46 | * Input: "{[]}" 47 | * Output: true 48 | * 49 | * 50 | */ 51 | pub struct Solution {} 52 | 53 | // problem: https://leetcode.com/problems/valid-parentheses/ 54 | // discuss: https://leetcode.com/problems/valid-parentheses/discuss/?currentPage=1&orderBy=most_votes&query= 55 | 56 | // submission codes start here 57 | 58 | impl Solution { 59 | pub fn is_valid(s: String) -> bool { 60 | let mut stack: Vec = Vec::new(); 61 | for ch in s.chars().into_iter() { 62 | match stack.last() { 63 | None => {} 64 | Some(&last) => { 65 | if Solution::pair(last, ch) { 66 | stack.pop(); 67 | continue; 68 | } 69 | } 70 | } 71 | stack.push(ch); 72 | } 73 | stack.is_empty() 74 | } 75 | 76 | #[inline(always)] 77 | fn pair(open: char, close: char) -> bool { 78 | (open == '{' && close == '}') 79 | || (open == '(' && close == ')') 80 | || (open == '[' && close == ']') 81 | } 82 | } 83 | 84 | // submission codes end 85 | 86 | #[cfg(test)] 87 | mod tests { 88 | use super::*; 89 | 90 | #[test] 91 | fn test_20() { 92 | assert_eq!(Solution::is_valid("()[]{}".to_string()), true); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/solution/s0022_generate_parentheses.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [22] Generate Parentheses 3 | * 4 | * 5 | * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 6 | * 7 | * 8 | * 9 | * For example, given n = 3, a solution set is: 10 | * 11 | * 12 | * [ 13 | * "((()))", 14 | * "(()())", 15 | * "(())()", 16 | * "()(())", 17 | * "()()()" 18 | * ] 19 | * 20 | */ 21 | pub struct Solution {} 22 | 23 | // problem: https://leetcode.com/problems/generate-parentheses/ 24 | // discuss: https://leetcode.com/problems/generate-parentheses/discuss/?currentPage=1&orderBy=most_votes&query= 25 | 26 | // submission codes start here 27 | 28 | // DFS 29 | impl Solution { 30 | pub fn generate_parenthesis(n: i32) -> Vec { 31 | if n < 1 { 32 | return vec![]; 33 | } 34 | let mut result = Vec::new(); 35 | Solution::dfs(n, 0, 0, &mut result, String::new()); 36 | result 37 | } 38 | 39 | fn dfs(n: i32, left: i32, right: i32, result: &mut Vec, mut path: String) { 40 | if left == n && right == n { 41 | result.push(path); 42 | return; 43 | } 44 | if left < n { 45 | let mut new_path = path.clone(); 46 | new_path.push('('); 47 | Solution::dfs(n, left + 1, right, result, new_path); 48 | } 49 | if right < left { 50 | // reuse path to avoid clone overhead 51 | path.push(')'); 52 | Solution::dfs(n, left, right + 1, result, path); 53 | } 54 | } 55 | } 56 | 57 | // submission codes end 58 | 59 | #[cfg(test)] 60 | mod tests { 61 | use super::*; 62 | 63 | #[test] 64 | fn test_22() { 65 | assert_eq!(Solution::generate_parenthesis(1), vec!["()"]); 66 | assert_eq!(Solution::generate_parenthesis(2), vec!["(())", "()()"]); 67 | assert_eq!( 68 | Solution::generate_parenthesis(3), 69 | vec!["((()))", "(()())", "(())()", "()(())", "()()()"] 70 | ); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/solution/s0028_implement_strstr.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [28] Implement strStr() 3 | * 4 | * Implement strStr(). 5 | * 6 | * Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 7 | * 8 | * Example 1: 9 | * 10 | * 11 | * Input: haystack = "hello", needle = "ll" 12 | * Output: 2 13 | * 14 | * 15 | * Example 2: 16 | * 17 | * 18 | * Input: haystack = "aaaaa", needle = "bba" 19 | * Output: -1 20 | * 21 | * 22 | * Clarification: 23 | * 24 | * What should we return when needle is an empty string? This is a great question to ask during an interview. 25 | * 26 | * For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf(). 27 | * 28 | */ 29 | pub struct Solution {} 30 | 31 | // problem: https://leetcode.com/problems/implement-strstr/ 32 | // discuss: https://leetcode.com/problems/implement-strstr/discuss/?currentPage=1&orderBy=most_votes&query= 33 | 34 | // submission codes start here 35 | 36 | impl Solution { 37 | pub fn str_str(haystack: String, needle: String) -> i32 { 38 | if needle.is_empty() { 39 | return 0; 40 | } 41 | haystack.find(&needle).map_or(-1_i32, |v| v as i32) 42 | } 43 | } 44 | 45 | // submission codes end 46 | 47 | #[cfg(test)] 48 | mod tests { 49 | use super::*; 50 | 51 | #[test] 52 | fn test_28() { 53 | assert_eq!(Solution::str_str("hello".to_string(), "ll".to_string()), 2) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/solution/s0029_divide_two_integers.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [29] Divide Two Integers 3 | * 4 | * Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. 5 | * 6 | * Return the quotient after dividing dividend by divisor. 7 | * 8 | * The integer division should truncate toward zero. 9 | * 10 | * Example 1: 11 | * 12 | * 13 | * Input: dividend = 10, divisor = 3 14 | * Output: 3 15 | * 16 | * Example 2: 17 | * 18 | * 19 | * Input: dividend = 7, divisor = -3 20 | * Output: -2 21 | * 22 | * Note: 23 | * 24 | * 25 | * Both dividend and divisor will be 32-bit signed integers. 26 | * The divisor will never be 0. 27 | * Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31, 2^31 - 1]. For the purpose of this problem, assume that your function returns 2^31 - 1 when the division result overflows. 28 | * 29 | * 30 | */ 31 | pub struct Solution {} 32 | 33 | // problem: https://leetcode.com/problems/divide-two-integers/ 34 | // discuss: https://leetcode.com/problems/divide-two-integers/discuss/?currentPage=1&orderBy=most_votes&query= 35 | 36 | // submission codes start here 37 | 38 | impl Solution { 39 | pub fn divide(dividend: i32, divisor: i32) -> i32 { 40 | 0 41 | } 42 | } 43 | 44 | // submission codes end 45 | 46 | #[cfg(test)] 47 | mod tests { 48 | use super::*; 49 | 50 | #[test] 51 | fn test_29() {} 52 | } 53 | -------------------------------------------------------------------------------- /src/solution/s0034_find_first_and_last_position_of_element_in_sorted_array.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [34] Find First and Last Position of Element in Sorted Array 3 | * 4 | * Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. 5 | * 6 | * Your algorithm's runtime complexity must be in the order of O(log n). 7 | * 8 | * If the target is not found in the array, return [-1, -1]. 9 | * 10 | * Example 1: 11 | * 12 | * 13 | * Input: nums = [5,7,7,8,8,10], target = 8 14 | * Output: [3,4] 15 | * 16 | * Example 2: 17 | * 18 | * 19 | * Input: nums = [5,7,7,8,8,10], target = 6 20 | * Output: [-1,-1] 21 | * 22 | */ 23 | pub struct Solution {} 24 | 25 | // problem: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ 26 | // discuss: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= 27 | 28 | // submission codes start here 29 | 30 | // TODO 31 | impl Solution { 32 | pub fn search_range(nums: Vec, target: i32) -> Vec { 33 | vec![] 34 | } 35 | } 36 | 37 | // submission codes end 38 | 39 | #[cfg(test)] 40 | mod tests { 41 | use super::*; 42 | 43 | #[test] 44 | fn test_34() {} 45 | } 46 | -------------------------------------------------------------------------------- /src/solution/s0035_search_insert_position.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [35] Search Insert Position 3 | * 4 | * Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 5 | * 6 | * You may assume no duplicates in the array. 7 | * 8 | * Example 1: 9 | * 10 | * 11 | * Input: [1,3,5,6], 5 12 | * Output: 2 13 | * 14 | * 15 | * Example 2: 16 | * 17 | * 18 | * Input: [1,3,5,6], 2 19 | * Output: 1 20 | * 21 | * 22 | * Example 3: 23 | * 24 | * 25 | * Input: [1,3,5,6], 7 26 | * Output: 4 27 | * 28 | * 29 | * Example 4: 30 | * 31 | * 32 | * Input: [1,3,5,6], 0 33 | * Output: 0 34 | * 35 | * 36 | */ 37 | pub struct Solution {} 38 | 39 | // problem: https://leetcode.com/problems/search-insert-position/ 40 | // discuss: https://leetcode.com/problems/search-insert-position/discuss/?currentPage=1&orderBy=most_votes&query= 41 | 42 | // submission codes start here 43 | 44 | // TODO 45 | impl Solution { 46 | pub fn search_insert(nums: Vec, target: i32) -> i32 { 47 | 0 48 | } 49 | } 50 | 51 | // submission codes end 52 | 53 | #[cfg(test)] 54 | mod tests { 55 | use super::*; 56 | 57 | #[test] 58 | fn test_35() {} 59 | } 60 | -------------------------------------------------------------------------------- /src/solution/s0037_sudoku_solver.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [37] Sudoku Solver 3 | * 4 | * Write a program to solve a Sudoku puzzle by filling the empty cells. 5 | * 6 | * A sudoku solution must satisfy all of the following rules: 7 | * 8 | *
    9 | * Each of the digits 1-9 must occur exactly once in each row. 10 | * Each of the digits 1-9 must occur exactly once in each column. 11 | * Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. 12 | *
13 | * 14 | * Empty cells are indicated by the character '.'. 15 | * 16 | *
17 | * A sudoku puzzle... 18 | * 19 | *
20 | * ...and its solution numbers marked in red. 21 | * 22 | * Note: 23 | * 24 | * 25 | * The given board contain only digits 1-9 and the character '.'. 26 | * You may assume that the given Sudoku puzzle will have a single unique solution. 27 | * The given board size is always 9x9. 28 | * 29 | * 30 | */ 31 | pub struct Solution {} 32 | 33 | // problem: https://leetcode.com/problems/sudoku-solver/ 34 | // discuss: https://leetcode.com/problems/sudoku-solver/discuss/?currentPage=1&orderBy=most_votes&query= 35 | 36 | // submission codes start here 37 | 38 | // TODO 39 | impl Solution { 40 | pub fn solve_sudoku(board: &mut Vec>) {} 41 | } 42 | 43 | // submission codes end 44 | 45 | #[cfg(test)] 46 | mod tests { 47 | use super::*; 48 | 49 | #[test] 50 | fn test_37() {} 51 | } 52 | -------------------------------------------------------------------------------- /src/solution/s0038_count_and_say.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [38] Count and Say 3 | * 4 | * The count-and-say sequence is the sequence of integers with the first five terms as following: 5 | * 6 | * 7 | * 1. 1 8 | * 2. 11 9 | * 3. 21 10 | * 4. 1211 11 | * 5. 111221 12 | * 13 | * 14 | * 1 is read off as "one 1" or 11.
15 | * 11 is read off as "two 1s" or 21.
16 | * 21 is read off as "one 2, then one 1" or 1211. 17 | * 18 | * Given an integer n where 1 <= n <= 30, generate the n^th term of the count-and-say sequence. 19 | * 20 | * Note: Each term of the sequence of integers will be represented as a string. 21 | * 22 | * 23 | * 24 | * Example 1: 25 | * 26 | * 27 | * Input: 1 28 | * Output: "1" 29 | * 30 | * 31 | * Example 2: 32 | * 33 | * 34 | * Input: 4 35 | * Output: "1211" 36 | * 37 | */ 38 | pub struct Solution {} 39 | 40 | // problem: https://leetcode.com/problems/count-and-say/ 41 | // discuss: https://leetcode.com/problems/count-and-say/discuss/?currentPage=1&orderBy=most_votes&query= 42 | 43 | // submission codes start here 44 | 45 | use std::char::from_digit; 46 | impl Solution { 47 | pub fn count_and_say(n: i32) -> String { 48 | let mut res = vec!['1']; 49 | for _ in 0..n - 1 { 50 | let mut temp = Vec::new(); 51 | let mut i = 0_usize; 52 | while i < res.len() { 53 | let mut j = i + 1; 54 | while j < res.len() && res[j] == res[i] { 55 | j += 1; 56 | } 57 | temp.push(from_digit((j - i) as u32, 10).unwrap()); 58 | temp.push(res[i]); 59 | i = j; 60 | } 61 | res = temp; 62 | } 63 | res.iter().collect() 64 | } 65 | } 66 | 67 | // submission codes end 68 | 69 | #[cfg(test)] 70 | mod tests { 71 | use super::*; 72 | 73 | #[test] 74 | fn test_38() { 75 | assert_eq!(Solution::count_and_say(1), "1"); 76 | assert_eq!(Solution::count_and_say(2), "11"); 77 | assert_eq!(Solution::count_and_say(3), "21"); 78 | assert_eq!(Solution::count_and_say(4), "1211"); 79 | assert_eq!(Solution::count_and_say(5), "111221"); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/solution/s0042_trapping_rain_water.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [42] Trapping Rain Water 3 | * 4 | * Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. 5 | * 6 | *
7 | * The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! 8 | * 9 | * Example: 10 | * 11 | * 12 | * Input: [0,1,0,2,1,0,1,3,2,1,2,1] 13 | * Output: 6 14 | * 15 | */ 16 | pub struct Solution {} 17 | 18 | // problem: https://leetcode.com/problems/trapping-rain-water/ 19 | // discuss: https://leetcode.com/problems/trapping-rain-water/discuss/?currentPage=1&orderBy=most_votes&query= 20 | 21 | // submission codes start here 22 | 23 | // TODO 24 | impl Solution { 25 | pub fn trap(height: Vec) -> i32 { 26 | 0 27 | } 28 | } 29 | 30 | // submission codes end 31 | 32 | #[cfg(test)] 33 | mod tests { 34 | use super::*; 35 | 36 | #[test] 37 | fn test_42() {} 38 | } 39 | -------------------------------------------------------------------------------- /src/solution/s0043_multiply_strings.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [43] Multiply Strings 3 | * 4 | * Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: num1 = "2", num2 = "3" 10 | * Output: "6" 11 | * 12 | * Example 2: 13 | * 14 | * 15 | * Input: num1 = "123", num2 = "456" 16 | * Output: "56088" 17 | * 18 | * 19 | * Note: 20 | * 21 | *
    22 | * The length of both num1 and num2 is < 110. 23 | * Both num1 and num2 contain only digits 0-9. 24 | * Both num1 and num2 do not contain any leading zero, except the number 0 itself. 25 | * You must not use any built-in BigInteger library or convert the inputs to integer directly. 26 | *
27 | * 28 | */ 29 | pub struct Solution {} 30 | 31 | // problem: https://leetcode.com/problems/multiply-strings/ 32 | // discuss: https://leetcode.com/problems/multiply-strings/discuss/?currentPage=1&orderBy=most_votes&query= 33 | 34 | // submission codes start here 35 | 36 | // TODO 37 | use std::char::from_digit; 38 | use std::collections::VecDeque; 39 | impl Solution { 40 | pub fn multiply(num1: String, num2: String) -> String { 41 | let mut num1: Vec = num1.chars().map(|ch| ch.to_digit(10).unwrap()).collect(); 42 | let mut num2: Vec = num2.chars().map(|ch| ch.to_digit(10).unwrap()).collect(); 43 | let mut buffer = VecDeque::with_capacity(num2.len() + 1); 44 | let mut res: Vec = Vec::new(); 45 | let mut carry = 0_u32; 46 | num1.reverse(); 47 | num2.reverse(); 48 | for (i, multiplier) in num1.into_iter().enumerate() { 49 | buffer 50 | .pop_back() 51 | .and_then(|digit| Some(res.push(from_digit(digit, 10).unwrap()))); 52 | for &multiplicand in num2.iter() {} 53 | } 54 | res.reverse(); 55 | res.into_iter().collect() 56 | } 57 | } 58 | 59 | // submission codes end 60 | 61 | #[cfg(test)] 62 | mod tests { 63 | use super::*; 64 | 65 | #[test] 66 | fn test_43() {} 67 | } 68 | -------------------------------------------------------------------------------- /src/solution/s0044_wildcard_matching.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [44] Wildcard Matching 3 | * 4 | * Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. 5 | * 6 | * 7 | * '?' Matches any single character. 8 | * '*' Matches any sequence of characters (including the empty sequence). 9 | * 10 | * 11 | * The matching should cover the entire input string (not partial). 12 | * 13 | * Note: 14 | * 15 | * 16 | * s could be empty and contains only lowercase letters a-z. 17 | * p could be empty and contains only lowercase letters a-z, and characters like ? or *. 18 | * 19 | * 20 | * Example 1: 21 | * 22 | * 23 | * Input: 24 | * s = "aa" 25 | * p = "a" 26 | * Output: false 27 | * Explanation: "a" does not match the entire string "aa". 28 | * 29 | * 30 | * Example 2: 31 | * 32 | * 33 | * Input: 34 | * s = "aa" 35 | * p = "*" 36 | * Output: true 37 | * Explanation: '*' matches any sequence. 38 | * 39 | * 40 | * Example 3: 41 | * 42 | * 43 | * Input: 44 | * s = "cb" 45 | * p = "?a" 46 | * Output: false 47 | * Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. 48 | * 49 | * 50 | * Example 4: 51 | * 52 | * 53 | * Input: 54 | * s = "adceb" 55 | * p = "*a*b" 56 | * Output: true 57 | * Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". 58 | * 59 | * 60 | * Example 5: 61 | * 62 | * 63 | * Input: 64 | * s = "acdcb" 65 | * p = "a*c?b" 66 | * Output: false 67 | * 68 | * 69 | */ 70 | pub struct Solution {} 71 | 72 | // problem: https://leetcode.com/problems/wildcard-matching/ 73 | // discuss: https://leetcode.com/problems/wildcard-matching/discuss/?currentPage=1&orderBy=most_votes&query= 74 | 75 | // submission codes start here 76 | 77 | impl Solution { 78 | pub fn is_match(s: String, p: String) -> bool { 79 | false 80 | } 81 | } 82 | 83 | // submission codes end 84 | 85 | #[cfg(test)] 86 | mod tests { 87 | use super::*; 88 | 89 | #[test] 90 | fn test_44() {} 91 | } 92 | -------------------------------------------------------------------------------- /src/solution/s0045_jump_game_ii.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [45] Jump Game II 3 | * 4 | * Given an array of non-negative integers, you are initially positioned at the first index of the array. 5 | * 6 | * Each element in the array represents your maximum jump length at that position. 7 | * 8 | * Your goal is to reach the last index in the minimum number of jumps. 9 | * 10 | * Example: 11 | * 12 | * 13 | * Input: [2,3,1,1,4] 14 | * Output: 2 15 | * Explanation: The minimum number of jumps to reach the last index is 2. 16 | * Jump 1 step from index 0 to 1, then 3 steps to the last index. 17 | * 18 | * Note: 19 | * 20 | * You can assume that you can always reach the last index. 21 | * 22 | */ 23 | pub struct Solution {} 24 | 25 | // problem: https://leetcode.com/problems/jump-game-ii/ 26 | // discuss: https://leetcode.com/problems/jump-game-ii/discuss/?currentPage=1&orderBy=most_votes&query= 27 | 28 | // submission codes start here 29 | 30 | // TODO: shortest path from backward 31 | impl Solution { 32 | pub fn jump(nums: Vec) -> i32 { 33 | 0 34 | } 35 | } 36 | 37 | // submission codes end 38 | 39 | #[cfg(test)] 40 | mod tests { 41 | use super::*; 42 | 43 | #[test] 44 | fn test_45() {} 45 | } 46 | -------------------------------------------------------------------------------- /src/solution/s0046_permutations.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [46] Permutations 3 | * 4 | * Given a collection of distinct integers, return all possible permutations. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: [1,2,3] 10 | * Output: 11 | * [ 12 | * [1,2,3], 13 | * [1,3,2], 14 | * [2,1,3], 15 | * [2,3,1], 16 | * [3,1,2], 17 | * [3,2,1] 18 | * ] 19 | * 20 | * 21 | */ 22 | pub struct Solution {} 23 | 24 | // problem: https://leetcode.com/problems/permutations/ 25 | // discuss: https://leetcode.com/problems/permutations/discuss/?currentPage=1&orderBy=most_votes&query= 26 | 27 | // submission codes start here 28 | 29 | impl Solution { 30 | pub fn permute(nums: Vec) -> Vec> { 31 | if nums.len() <= 1 { 32 | return vec![nums]; 33 | } 34 | nums.iter() 35 | .flat_map(|&num| { 36 | let mut sub = nums.clone().into_iter().filter(|&x| x != num).collect(); 37 | Solution::permute(sub) 38 | .into_iter() 39 | .map(|vec| { 40 | let mut vec = vec; 41 | vec.push(num); 42 | vec 43 | }) 44 | .collect::>>() 45 | }) 46 | .collect() 47 | } 48 | } 49 | 50 | // submission codes end 51 | 52 | #[cfg(test)] 53 | mod tests { 54 | use super::*; 55 | 56 | #[test] 57 | fn test_46() { 58 | assert_eq!( 59 | Solution::permute(vec![1, 2, 3]), 60 | vec![ 61 | vec![3, 2, 1], 62 | vec![2, 3, 1], 63 | vec![3, 1, 2], 64 | vec![1, 3, 2], 65 | vec![2, 1, 3], 66 | vec![1, 2, 3], 67 | ] 68 | ) 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/solution/s0049_group_anagrams.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [49] Group Anagrams 3 | * 4 | * Given an array of strings, group anagrams together. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: ["eat", "tea", "tan", "ate", "nat", "bat"], 10 | * Output: 11 | * [ 12 | * ["ate","eat","tea"], 13 | * ["nat","tan"], 14 | * ["bat"] 15 | * ] 16 | * 17 | * Note: 18 | * 19 | * 20 | * All inputs will be in lowercase. 21 | * The order of your output does not matter. 22 | * 23 | * 24 | */ 25 | pub struct Solution {} 26 | 27 | // problem: https://leetcode.com/problems/group-anagrams/ 28 | // discuss: https://leetcode.com/problems/group-anagrams/discuss/?currentPage=1&orderBy=most_votes&query= 29 | 30 | // submission codes start here 31 | 32 | use std::collections::HashMap; 33 | impl Solution { 34 | pub fn group_anagrams(strs: Vec) -> Vec> { 35 | let mut map = HashMap::new(); 36 | for s in strs.into_iter() { 37 | let mut key = [0; 26]; 38 | for ch in s.chars() { 39 | key[(ch as u32 - 'a' as u32) as usize] += 1; 40 | } 41 | map.entry(key).or_insert(Vec::new()).push(s); 42 | } 43 | map.into_iter().map(|(_, v)| v).collect() 44 | } 45 | } 46 | 47 | // submission codes end 48 | 49 | #[cfg(test)] 50 | mod tests { 51 | use super::*; 52 | 53 | use std::collections::HashSet; 54 | // TODO: implement arbitrary match macro 55 | #[test] 56 | #[ignore] 57 | fn test_49() { 58 | assert_eq!( 59 | Solution::group_anagrams(vec_string!["eat", "tea", "tan", "ate", "nat", "bat"]), 60 | vec![ 61 | vec_string!["tan", "nat"], 62 | vec_string!["bat"], 63 | vec_string!["eat", "ate", "tea"], 64 | ] 65 | ); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/solution/s0050_powx_n.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [50] Pow(x, n) 3 | * 4 | * Implement pow(x, n), which calculates x raised to the power n (x^n). 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: 2.00000, 10 10 | * Output: 1024.00000 11 | * 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: 2.10000, 3 17 | * Output: 9.26100 18 | * 19 | * 20 | * Example 3: 21 | * 22 | * 23 | * Input: 2.00000, -2 24 | * Output: 0.25000 25 | * Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25 26 | * 27 | * 28 | * Note: 29 | * 30 | * 31 | * -100.0 < x < 100.0 32 | * n is a 32-bit signed integer, within the range [-2^31, 2^31 - 1] 33 | * 34 | * 35 | */ 36 | pub struct Solution {} 37 | 38 | // problem: https://leetcode.com/problems/powx-n/ 39 | // discuss: https://leetcode.com/problems/powx-n/discuss/?currentPage=1&orderBy=most_votes&query= 40 | 41 | // submission codes start here 42 | 43 | impl Solution { 44 | pub fn my_pow(x: f64, n: i32) -> f64 { 45 | x.powi(n) 46 | } 47 | } 48 | 49 | // submission codes end 50 | 51 | #[cfg(test)] 52 | mod tests { 53 | use super::*; 54 | 55 | #[test] 56 | fn test_50() { 57 | assert_eq!(Solution::my_pow(2.0, -2), 0.25); 58 | assert_eq!(Solution::my_pow(2.0, 4), 16.0); 59 | assert_eq!(Solution::my_pow(2.0, 5), 32.0); 60 | assert_eq!(Solution::my_pow(2.0, 1), 2.0); 61 | assert_eq!(Solution::my_pow(2.0, -1), 0.5); 62 | assert_eq!(Solution::my_pow(2.0, 10), 1024.0); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/solution/s0053_maximum_subarray.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [53] Maximum Subarray 3 | * 4 | * Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: [-2,1,-3,4,-1,2,1,-5,4], 10 | * Output: 6 11 | * Explanation: [4,-1,2,1] has the largest sum = 6. 12 | * 13 | * 14 | * Follow up: 15 | * 16 | * If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 17 | * 18 | */ 19 | pub struct Solution {} 20 | 21 | // problem: https://leetcode.com/problems/maximum-subarray/ 22 | // discuss: https://leetcode.com/problems/maximum-subarray/discuss/?currentPage=1&orderBy=most_votes&query= 23 | 24 | // submission codes start here 25 | 26 | impl Solution { 27 | pub fn max_sub_array(nums: Vec) -> i32 { 28 | let mut j = 0_usize; 29 | let mut max = i32::min_value(); 30 | let mut curr = 0; 31 | for j in 0..nums.len() { 32 | curr += nums[j]; 33 | max = i32::max(max, curr); 34 | if curr <= 0 { 35 | curr = 0; 36 | } 37 | } 38 | max 39 | } 40 | } 41 | 42 | // submission codes end 43 | 44 | #[cfg(test)] 45 | mod tests { 46 | use super::*; 47 | 48 | #[test] 49 | fn test_53() { 50 | assert_eq!( 51 | Solution::max_sub_array(vec![-2, 1, -3, 4, -1, 2, 1, -5, 4]), 52 | 6 53 | ); 54 | assert_eq!(Solution::max_sub_array(vec![-8]), -8); 55 | assert_eq!(Solution::max_sub_array(vec![-8, -2]), -2); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/solution/s0055_jump_game.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [55] Jump Game 3 | * 4 | * Given an array of non-negative integers, you are initially positioned at the first index of the array. 5 | * 6 | * Each element in the array represents your maximum jump length at that position. 7 | * 8 | * Determine if you are able to reach the last index. 9 | * 10 | * Example 1: 11 | * 12 | * 13 | * Input: [2,3,1,1,4] 14 | * Output: true 15 | * Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 16 | * 17 | * 18 | * Example 2: 19 | * 20 | * 21 | * Input: [3,2,1,0,4] 22 | * Output: false 23 | * Explanation: You will always arrive at index 3 no matter what. Its maximum 24 | * jump length is 0, which makes it impossible to reach the last index. 25 | * 26 | * 27 | */ 28 | pub struct Solution {} 29 | 30 | // problem: https://leetcode.com/problems/jump-game/ 31 | // discuss: https://leetcode.com/problems/jump-game/discuss/?currentPage=1&orderBy=most_votes&query= 32 | 33 | // submission codes start here 34 | 35 | impl Solution { 36 | pub fn can_jump(nums: Vec) -> bool { 37 | let mut max_idx = 0_usize; 38 | let mut start = 0_usize; 39 | while start < nums.len() && start <= max_idx { 40 | max_idx = usize::max(start + nums[start] as usize, max_idx); 41 | start += 1; 42 | } 43 | return max_idx >= (nums.len() - 1); 44 | } 45 | } 46 | 47 | // submission codes end 48 | 49 | #[cfg(test)] 50 | mod tests { 51 | use super::*; 52 | 53 | #[test] 54 | fn test_55() { 55 | assert_eq!(Solution::can_jump(vec![2, 3, 1, 1, 4]), true); 56 | assert_eq!(Solution::can_jump(vec![3, 2, 1, 0, 4]), false); 57 | assert_eq!(Solution::can_jump(vec![2, 3, 1, 1, 0, 0, 0, 4]), false); 58 | assert_eq!(Solution::can_jump(vec![8, 3, 1, 1, 0, 0, 0, 4]), true); 59 | assert_eq!(Solution::can_jump(vec![0]), true); 60 | assert_eq!(Solution::can_jump(vec![1, 1, 2, 2, 0, 1, 1]), true); 61 | assert_eq!( 62 | Solution::can_jump(vec![1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]), 63 | true 64 | ); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/solution/s0058_length_of_last_word.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [58] Length of Last Word 3 | * 4 | * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 5 | * 6 | * If the last word does not exist, return 0. 7 | * 8 | * Note: A word is defined as a character sequence consists of non-space characters only. 9 | * 10 | * Example: 11 | * 12 | * Input: "Hello World" 13 | * Output: 5 14 | * 15 | * 16 | */ 17 | pub struct Solution {} 18 | 19 | // problem: https://leetcode.com/problems/length-of-last-word/ 20 | // discuss: https://leetcode.com/problems/length-of-last-word/discuss/?currentPage=1&orderBy=most_votes&query= 21 | 22 | // submission codes start here 23 | 24 | impl Solution { 25 | pub fn length_of_last_word(s: String) -> i32 { 26 | let seq: Vec = s.chars().rev().collect(); 27 | let mut result = 0; 28 | let mut find = false; 29 | for ch in seq { 30 | if ch == ' ' && find { 31 | break; 32 | } 33 | if ch != ' ' { 34 | find = true; 35 | result += 1; 36 | } 37 | } 38 | result 39 | } 40 | } 41 | 42 | // submission codes end 43 | 44 | #[cfg(test)] 45 | mod tests { 46 | use super::*; 47 | 48 | #[test] 49 | fn test_58() { 50 | assert_eq!(Solution::length_of_last_word("Hello World".to_owned()), 5); 51 | assert_eq!(Solution::length_of_last_word(" ".to_owned()), 0); 52 | assert_eq!(Solution::length_of_last_word("".to_owned()), 0); 53 | assert_eq!(Solution::length_of_last_word(" rrrrr ".to_owned()), 5); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/solution/s0060_permutation_sequence.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [60] Permutation Sequence 3 | * 4 | * The set [1,2,3,...,n] contains a total of n! unique permutations. 5 | * 6 | * By listing and labeling all of the permutations in order, we get the following sequence for n = 3: 7 | * 8 | *
    9 | * "123" 10 | * "132" 11 | * "213" 12 | * "231" 13 | * "312" 14 | * "321" 15 | *
16 | * 17 | * Given n and k, return the k^th permutation sequence. 18 | * 19 | * Note: 20 | * 21 | * 22 | * Given n will be between 1 and 9 inclusive. 23 | * Given k will be between 1 and n! inclusive. 24 | * 25 | * 26 | * Example 1: 27 | * 28 | * 29 | * Input: n = 3, k = 3 30 | * Output: "213" 31 | * 32 | * 33 | * Example 2: 34 | * 35 | * 36 | * Input: n = 4, k = 9 37 | * Output: "2314" 38 | * 39 | * 40 | */ 41 | pub struct Solution {} 42 | 43 | // problem: https://leetcode.com/problems/permutation-sequence/ 44 | // discuss: https://leetcode.com/problems/permutation-sequence/discuss/?currentPage=1&orderBy=most_votes&query= 45 | 46 | // submission codes start here 47 | 48 | // target: split k = i! + j! + ... 49 | use std::char::from_digit; 50 | impl Solution { 51 | pub fn get_permutation(n: i32, k: i32) -> String { 52 | let factorials = [0, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]; 53 | let mut k = k; 54 | let mut i = n; 55 | let mut res = String::new(); 56 | while i > 0 { 57 | if k > factorials[i as usize] { 58 | let round = k / factorials[i as usize]; 59 | if round >= n {} 60 | } else { 61 | i -= 1; 62 | } 63 | } 64 | res 65 | } 66 | } 67 | 68 | // submission codes end 69 | 70 | #[cfg(test)] 71 | mod tests { 72 | use super::*; 73 | 74 | #[test] 75 | fn test_60() {} 76 | } 77 | -------------------------------------------------------------------------------- /src/solution/s0061_rotate_list.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [61] Rotate List 3 | * 4 | * Given a linked list, rotate the list to the right by k places, where k is non-negative. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: 1->2->3->4->5->NULL, k = 2 10 | * Output: 4->5->1->2->3->NULL 11 | * Explanation: 12 | * rotate 1 steps to the right: 5->1->2->3->4->NULL 13 | * rotate 2 steps to the right: 4->5->1->2->3->NULL 14 | * 15 | * 16 | * Example 2: 17 | * 18 | * 19 | * Input: 0->1->2->NULL, k = 4 20 | * Output: 2->0->1->NULL 21 | * Explanation: 22 | * rotate 1 steps to the right: 2->0->1->NULL 23 | * rotate 2 steps to the right: 1->2->0->NULL 24 | * rotate 3 steps to the right: 0->1->2->NULL 25 | * rotate 4 steps to the right: 2->0->1->NULL 26 | * 27 | */ 28 | pub struct Solution {} 29 | use crate::util::linked_list::{to_list, ListNode}; 30 | 31 | // problem: https://leetcode.com/problems/rotate-list/ 32 | // discuss: https://leetcode.com/problems/rotate-list/discuss/?currentPage=1&orderBy=most_votes&query= 33 | 34 | // submission codes start here 35 | 36 | impl Solution { 37 | pub fn rotate_right(head: Option>, k: i32) -> Option> { 38 | None 39 | } 40 | } 41 | 42 | // submission codes end 43 | 44 | #[cfg(test)] 45 | mod tests { 46 | use super::*; 47 | 48 | #[test] 49 | fn test_61() {} 50 | } 51 | -------------------------------------------------------------------------------- /src/solution/s0064_minimum_path_sum.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [64] Minimum Path Sum 3 | * 4 | * Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 5 | * 6 | * Note: You can only move either down or right at any point in time. 7 | * 8 | * Example: 9 | * 10 | * 11 | * Input: 12 | * [ 13 | * [1,3,1], 14 | * [1,5,1], 15 | * [4,2,1] 16 | * ] 17 | * Output: 7 18 | * Explanation: Because the path 1→3→1→1→1 minimizes the sum. 19 | * 20 | * 21 | */ 22 | pub struct Solution {} 23 | 24 | // problem: https://leetcode.com/problems/minimum-path-sum/ 25 | // discuss: https://leetcode.com/problems/minimum-path-sum/discuss/?currentPage=1&orderBy=most_votes&query= 26 | 27 | // submission codes start here 28 | 29 | impl Solution { 30 | pub fn min_path_sum(grid: Vec>) -> i32 { 31 | let (height, width) = (grid.len(), grid[0].len()); 32 | let mut grid = grid; 33 | let mut step = 1; 34 | while step <= height + width - 2 { 35 | for x in 0..(step + 1) { 36 | let y = step - x; 37 | if x >= height || y >= width { 38 | continue; 39 | } 40 | if x < 1 { 41 | grid[x][y] += grid[x][y - 1]; 42 | } else if y < 1 { 43 | grid[x][y] += grid[x - 1][y]; 44 | } else { 45 | grid[x][y] += i32::min(grid[x][y - 1], grid[x - 1][y]); 46 | } 47 | } 48 | step += 1; 49 | } 50 | grid[height - 1][width - 1] 51 | } 52 | } 53 | 54 | // submission codes end 55 | 56 | #[cfg(test)] 57 | mod tests { 58 | use super::*; 59 | 60 | #[test] 61 | fn test_64() { 62 | assert_eq!(Solution::min_path_sum(vec![vec![2]]), 2); 63 | assert_eq!( 64 | Solution::min_path_sum(vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1],]), 65 | 7 66 | ); 67 | assert_eq!(Solution::min_path_sum(vec![vec![1, 3, 1],]), 5); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/solution/s0065_valid_number.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [65] Valid Number 3 | * 4 | * Validate if a given string can be interpreted as a decimal number. 5 | * 6 | * Some examples:
7 | * "0" => true
8 | * " 0.1 " => true
9 | * "abc" => false
10 | * "1 a" => false
11 | * "2e10" => true
12 | * " -90e3 " => true
13 | * " 1e" => false
14 | * "e3" => false
15 | * " 6e-1" => true
16 | * " 99e2.5 " => false
17 | * "53.5e93" => true
18 | * " --6 " => false
19 | * "-+3" => false
20 | * "95a54e53" => false 21 | * 22 | * Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number: 23 | * 24 | * 25 | * Numbers 0-9 26 | * Exponent - "e" 27 | * Positive/negative sign - "+"/"-" 28 | * Decimal point - "." 29 | * 30 | * 31 | * Of course, the context of these characters also matters in the input. 32 | * 33 | * Update (2015-02-10):
34 | * The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition. 35 | * 36 | */ 37 | pub struct Solution {} 38 | 39 | // problem: https://leetcode.com/problems/valid-number/ 40 | // discuss: https://leetcode.com/problems/valid-number/discuss/?currentPage=1&orderBy=most_votes&query= 41 | 42 | // submission codes start here 43 | 44 | // hope that regex was included in std library... 45 | // TODO: NFA 46 | impl Solution { 47 | pub fn is_number(s: String) -> bool { 48 | false 49 | } 50 | } 51 | 52 | // submission codes end 53 | 54 | #[cfg(test)] 55 | mod tests { 56 | use super::*; 57 | 58 | #[test] 59 | fn test_65() {} 60 | } 61 | -------------------------------------------------------------------------------- /src/solution/s0066_plus_one.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [66] Plus One 3 | * 4 | * Given a non-empty array of digits representing a non-negative integer, plus one to the integer. 5 | * 6 | * The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. 7 | * 8 | * You may assume the integer does not contain any leading zero, except the number 0 itself. 9 | * 10 | * Example 1: 11 | * 12 | * 13 | * Input: [1,2,3] 14 | * Output: [1,2,4] 15 | * Explanation: The array represents the integer 123. 16 | * 17 | * 18 | * Example 2: 19 | * 20 | * 21 | * Input: [4,3,2,1] 22 | * Output: [4,3,2,2] 23 | * Explanation: The array represents the integer 4321. 24 | * 25 | * 26 | */ 27 | pub struct Solution {} 28 | 29 | // problem: https://leetcode.com/problems/plus-one/ 30 | // discuss: https://leetcode.com/problems/plus-one/discuss/?currentPage=1&orderBy=most_votes&query= 31 | 32 | // submission codes start here 33 | 34 | impl Solution { 35 | pub fn plus_one(digits: Vec) -> Vec { 36 | let mut digits = digits; 37 | let mut carry = 0; 38 | for i in (0..digits.len()).rev() { 39 | digits[i] = if digits[i] == 9 { 40 | carry = 1; 41 | 0 42 | } else { 43 | carry = 0; 44 | digits[i] + 1 45 | }; 46 | if carry == 0 { 47 | break; 48 | } 49 | } 50 | if carry > 0 { 51 | digits.insert(0, 1); 52 | } 53 | digits 54 | } 55 | } 56 | 57 | // submission codes end 58 | 59 | #[cfg(test)] 60 | mod tests { 61 | use super::*; 62 | 63 | #[test] 64 | fn test_66() { 65 | assert_eq!(Solution::plus_one(vec![0]), vec![1]); 66 | assert_eq!(Solution::plus_one(vec![9, 9, 9, 9]), vec![1, 0, 0, 0, 0]); 67 | assert_eq!( 68 | Solution::plus_one(vec![1, 0, 9, 9, 9, 9]), 69 | vec![1, 1, 0, 0, 0, 0] 70 | ); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/solution/s0067_add_binary.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [67] Add Binary 3 | * 4 | * Given two binary strings, return their sum (also a binary string). 5 | * 6 | * The input strings are both non-empty and contains only characters 1 or 0. 7 | * 8 | * Example 1: 9 | * 10 | * 11 | * Input: a = "11", b = "1" 12 | * Output: "100" 13 | * 14 | * Example 2: 15 | * 16 | * 17 | * Input: a = "1010", b = "1011" 18 | * Output: "10101" 19 | * 20 | */ 21 | pub struct Solution {} 22 | 23 | // problem: https://leetcode.com/problems/add-binary/ 24 | // discuss: https://leetcode.com/problems/add-binary/discuss/?currentPage=1&orderBy=most_votes&query= 25 | 26 | // submission codes start here 27 | 28 | use std::char::from_digit; 29 | impl Solution { 30 | pub fn add_binary(a: String, b: String) -> String { 31 | let mut buf = Vec::with_capacity(usize::max(a.len(), b.len()) + 1); 32 | let mut a: Vec = a.chars().collect(); 33 | let mut b: Vec = b.chars().collect(); 34 | let mut carry = 0; 35 | while !(a.is_empty() && b.is_empty()) { 36 | let mut sum = a.pop().map_or(0, |ch| ch.to_digit(10).unwrap()) 37 | + b.pop().map_or(0, |ch| ch.to_digit(10).unwrap()) 38 | + carry; 39 | if sum > 1 { 40 | sum -= 2; 41 | carry = 1; 42 | } else { 43 | carry = 0; 44 | } 45 | buf.push(from_digit(sum, 10).unwrap()) 46 | } 47 | if carry > 0 { 48 | buf.push('1') 49 | } 50 | buf.into_iter().rev().collect() 51 | } 52 | } 53 | 54 | // submission codes end 55 | 56 | #[cfg(test)] 57 | mod tests { 58 | use super::*; 59 | 60 | #[test] 61 | fn test_67() { 62 | assert_eq!( 63 | Solution::add_binary("0".to_owned(), "0".to_owned()), 64 | "0".to_owned() 65 | ); 66 | assert_eq!( 67 | Solution::add_binary("1010".to_owned(), "1011".to_owned()), 68 | "10101".to_owned() 69 | ); 70 | assert_eq!( 71 | Solution::add_binary("11".to_owned(), "1".to_owned()), 72 | "100".to_owned() 73 | ); 74 | assert_eq!( 75 | Solution::add_binary("1111".to_owned(), "1111".to_owned()), 76 | "11110".to_owned() 77 | ); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/solution/s0069_sqrtx.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [69] Sqrt(x) 3 | * 4 | * Implement int sqrt(int x). 5 | * 6 | * Compute and return the square root of x, where x is guaranteed to be a non-negative integer. 7 | * 8 | * Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. 9 | * 10 | * Example 1: 11 | * 12 | * 13 | * Input: 4 14 | * Output: 2 15 | * 16 | * 17 | * Example 2: 18 | * 19 | * 20 | * Input: 8 21 | * Output: 2 22 | * Explanation: The square root of 8 is 2.82842..., and since 23 | * the decimal part is truncated, 2 is returned. 24 | * 25 | * 26 | */ 27 | pub struct Solution {} 28 | 29 | // problem: https://leetcode.com/problems/sqrtx/ 30 | // discuss: https://leetcode.com/problems/sqrtx/discuss/?currentPage=1&orderBy=most_votes&query= 31 | 32 | // submission codes start here 33 | 34 | // Newton-Raphson for: root^2 - n = 0 35 | // Tangent equation: y = 2 * root * x - (root^2 + n) 36 | // Zero point: (root^2 + n) / (2 * root) 37 | impl Solution { 38 | pub fn my_sqrt(x: i32) -> i32 { 39 | let mut size = x; 40 | let mut base = 1; 41 | while size > 1 { 42 | let half = size / 2; 43 | let mid = base + half; 44 | if mid <= x / mid { 45 | base = mid; 46 | } 47 | size -= half; 48 | } 49 | base 50 | } 51 | } 52 | 53 | // submission codes end 54 | 55 | #[cfg(test)] 56 | mod tests { 57 | use super::*; 58 | 59 | #[test] 60 | fn test_69() { 61 | assert_eq!(Solution::my_sqrt(8), 2); 62 | assert_eq!(Solution::my_sqrt(16), 4); 63 | assert_eq!(Solution::my_sqrt(17), 4); 64 | assert_eq!(Solution::my_sqrt(81), 9); 65 | assert_eq!(Solution::my_sqrt(82), 9); 66 | assert_eq!(Solution::my_sqrt(100480577), 10024); 67 | assert_eq!(Solution::my_sqrt(100480575), 10023); 68 | assert_eq!(Solution::my_sqrt(100480575), 10023); 69 | assert_eq!(Solution::my_sqrt(80), 8); 70 | assert_eq!(Solution::my_sqrt(2), 1); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/solution/s0070_climbing_stairs.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [70] Climbing Stairs 3 | * 4 | * You are climbing a stair case. It takes n steps to reach to the top. 5 | * 6 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 7 | * 8 | * Note: Given n will be a positive integer. 9 | * 10 | * Example 1: 11 | * 12 | * 13 | * Input: 2 14 | * Output: 2 15 | * Explanation: There are two ways to climb to the top. 16 | * 1. 1 step + 1 step 17 | * 2. 2 steps 18 | * 19 | * 20 | * Example 2: 21 | * 22 | * 23 | * Input: 3 24 | * Output: 3 25 | * Explanation: There are three ways to climb to the top. 26 | * 1. 1 step + 1 step + 1 step 27 | * 2. 1 step + 2 steps 28 | * 3. 2 steps + 1 step 29 | * 30 | * 31 | */ 32 | pub struct Solution {} 33 | 34 | // problem: https://leetcode.com/problems/climbing-stairs/ 35 | // discuss: https://leetcode.com/problems/climbing-stairs/discuss/?currentPage=1&orderBy=most_votes&query= 36 | 37 | // submission codes start here 38 | 39 | // Bottom-up DP 40 | impl Solution { 41 | pub fn climb_stairs(n: i32) -> i32 { 42 | let n = n as usize; 43 | if n == 1 { 44 | return 1; 45 | } 46 | if n == 2 { 47 | return 2; 48 | } 49 | let (mut prev, mut curr) = (1, 2); 50 | for i in 2..n { 51 | let next = prev + curr; 52 | prev = curr; 53 | curr = next; 54 | } 55 | curr 56 | } 57 | } 58 | 59 | // submission codes end 60 | 61 | #[cfg(test)] 62 | mod tests { 63 | use super::*; 64 | 65 | #[test] 66 | fn test_70() { 67 | assert_eq!(Solution::climb_stairs(3), 3); 68 | assert_eq!(Solution::climb_stairs(4), 5); 69 | assert_eq!(Solution::climb_stairs(5), 8); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/solution/s0072_edit_distance.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [72] Edit Distance 3 | * 4 | * Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. 5 | * 6 | * You have the following 3 operations permitted on a word: 7 | * 8 | *
    9 | * Insert a character 10 | * Delete a character 11 | * Replace a character 12 | *
13 | * 14 | * Example 1: 15 | * 16 | * 17 | * Input: word1 = "horse", word2 = "ros" 18 | * Output: 3 19 | * Explanation: 20 | * horse -> rorse (replace 'h' with 'r') 21 | * rorse -> rose (remove 'r') 22 | * rose -> ros (remove 'e') 23 | * 24 | * 25 | * Example 2: 26 | * 27 | * 28 | * Input: word1 = "intention", word2 = "execution" 29 | * Output: 5 30 | * Explanation: 31 | * intention -> inention (remove 't') 32 | * inention -> enention (replace 'i' with 'e') 33 | * enention -> exention (replace 'n' with 'x') 34 | * exention -> exection (replace 'n' with 'c') 35 | * exection -> execution (insert 'u') 36 | * 37 | * 38 | */ 39 | pub struct Solution {} 40 | 41 | // problem: https://leetcode.com/problems/edit-distance/ 42 | // discuss: https://leetcode.com/problems/edit-distance/discuss/?currentPage=1&orderBy=most_votes&query= 43 | 44 | // submission codes start here 45 | 46 | impl Solution { 47 | pub fn min_distance(word1: String, word2: String) -> i32 { 48 | 0 49 | } 50 | } 51 | 52 | // submission codes end 53 | 54 | #[cfg(test)] 55 | mod tests { 56 | use super::*; 57 | 58 | #[test] 59 | fn test_72() {} 60 | } 61 | -------------------------------------------------------------------------------- /src/solution/s0073_set_matrix_zeroes.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [73] Set Matrix Zeroes 3 | * 4 | * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: 10 | * [ 11 | * [1,1,1], 12 | * [1,0,1], 13 | * [1,1,1] 14 | * ] 15 | * Output: 16 | * [ 17 | * [1,0,1], 18 | * [0,0,0], 19 | * [1,0,1] 20 | * ] 21 | * 22 | * 23 | * Example 2: 24 | * 25 | * 26 | * Input: 27 | * [ 28 | * [0,1,2,0], 29 | * [3,4,5,2], 30 | * [1,3,1,5] 31 | * ] 32 | * Output: 33 | * [ 34 | * [0,0,0,0], 35 | * [0,4,5,0], 36 | * [0,3,1,0] 37 | * ] 38 | * 39 | * 40 | * Follow up: 41 | * 42 | * 43 | * A straight forward solution using O(mn) space is probably a bad idea. 44 | * A simple improvement uses O(m + n) space, but still not the best solution. 45 | * Could you devise a constant space solution? 46 | * 47 | * 48 | */ 49 | pub struct Solution {} 50 | 51 | // problem: https://leetcode.com/problems/set-matrix-zeroes/ 52 | // discuss: https://leetcode.com/problems/set-matrix-zeroes/discuss/?currentPage=1&orderBy=most_votes&query= 53 | 54 | // submission codes start here 55 | 56 | impl Solution { 57 | pub fn set_zeroes(matrix: &mut Vec>) {} 58 | } 59 | 60 | // submission codes end 61 | 62 | #[cfg(test)] 63 | mod tests { 64 | use super::*; 65 | 66 | #[test] 67 | fn test_73() {} 68 | } 69 | -------------------------------------------------------------------------------- /src/solution/s0076_minimum_window_substring.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [76] Minimum Window Substring 3 | * 4 | * Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: S = "ADOBECODEBANC", T = "ABC" 10 | * Output: "BANC" 11 | * 12 | * 13 | * Note: 14 | * 15 | * 16 | * If there is no such window in S that covers all characters in T, return the empty string "". 17 | * If there is such window, you are guaranteed that there will always be only one unique minimum window in S. 18 | * 19 | * 20 | */ 21 | pub struct Solution {} 22 | 23 | // problem: https://leetcode.com/problems/minimum-window-substring/ 24 | // discuss: https://leetcode.com/problems/minimum-window-substring/discuss/?currentPage=1&orderBy=most_votes&query= 25 | 26 | // submission codes start here 27 | use std::collections::HashMap; 28 | impl Solution { 29 | pub fn min_window(s: String, t: String) -> String { 30 | if t.is_empty() || t.len() > s.len() { 31 | return "".to_owned(); 32 | } 33 | let (mut start, mut end) = (0_usize, 0_usize); 34 | let mut result = (0_usize, 0_usize); 35 | loop {} 36 | s[result.0..result.1].to_owned() 37 | } 38 | 39 | fn count_char(s: String) -> HashMap { 40 | let mut res = HashMap::new(); 41 | for ch in s.chars().into_iter() { 42 | *res.entry(ch).or_insert(0) += 1; 43 | } 44 | res 45 | } 46 | } 47 | 48 | // submission codes end 49 | 50 | #[cfg(test)] 51 | mod tests { 52 | use super::*; 53 | 54 | #[test] 55 | fn test_76() {} 56 | } 57 | -------------------------------------------------------------------------------- /src/solution/s0077_combinations.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [77] Combinations 3 | * 4 | * Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: n = 4, k = 2 10 | * Output: 11 | * [ 12 | * [2,4], 13 | * [3,4], 14 | * [2,3], 15 | * [1,2], 16 | * [1,3], 17 | * [1,4], 18 | * ] 19 | * 20 | * 21 | */ 22 | pub struct Solution {} 23 | 24 | // problem: https://leetcode.com/problems/combinations/ 25 | // discuss: https://leetcode.com/problems/combinations/discuss/?currentPage=1&orderBy=most_votes&query= 26 | 27 | // submission codes start here 28 | 29 | impl Solution { 30 | pub fn combine(n: i32, k: i32) -> Vec> { 31 | let mut res: Vec> = Vec::new(); 32 | Solution::backtrack(1, n, k, vec![], &mut res); 33 | res 34 | } 35 | 36 | fn backtrack(start: i32, end: i32, k: i32, curr: Vec, result: &mut Vec>) { 37 | if k < 1 { 38 | result.push(curr); 39 | return; 40 | } 41 | if end - start + 1 < k { 42 | // elements is not enough, return quickly 43 | return; 44 | } 45 | for i in start..end + 1 { 46 | let mut vec = curr.clone(); 47 | vec.push(i); 48 | Solution::backtrack(i + 1, end, k - 1, vec, result); 49 | } 50 | } 51 | } 52 | 53 | // submission codes end 54 | 55 | #[cfg(test)] 56 | mod tests { 57 | use super::*; 58 | 59 | #[test] 60 | fn test_77() { 61 | assert_eq!( 62 | Solution::combine(4, 2), 63 | vec![ 64 | vec![1, 2], 65 | vec![1, 3], 66 | vec![1, 4], 67 | vec![2, 3], 68 | vec![2, 4], 69 | vec![3, 4] 70 | ] 71 | ); 72 | assert_eq!(Solution::combine(1, 1), vec![vec![1]]); 73 | let empty: Vec> = vec![]; 74 | assert_eq!(Solution::combine(0, 1), empty); 75 | assert_eq!(Solution::combine(2, 1), vec![vec![1], vec![2]]); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/solution/s0078_subsets.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [78] Subsets 3 | * 4 | * Given a set of distinct integers, nums, return all possible subsets (the power set). 5 | * 6 | * Note: The solution set must not contain duplicate subsets. 7 | * 8 | * Example: 9 | * 10 | * 11 | * Input: nums = [1,2,3] 12 | * Output: 13 | * [ 14 | * [3], 15 | * [1], 16 | * [2], 17 | * [1,2,3], 18 | * [1,3], 19 | * [2,3], 20 | * [1,2], 21 | * [] 22 | * ] 23 | * 24 | */ 25 | pub struct Solution {} 26 | 27 | // problem: https://leetcode.com/problems/subsets/ 28 | // discuss: https://leetcode.com/problems/subsets/discuss/?currentPage=1&orderBy=most_votes&query= 29 | 30 | // submission codes start here 31 | 32 | impl Solution { 33 | pub fn subsets(nums: Vec) -> Vec> { 34 | let mut res = Vec::new(); 35 | Solution::backtrack(0, vec![], &nums, &mut res); 36 | res 37 | } 38 | 39 | fn backtrack(start: usize, mut curr: Vec, nums: &Vec, result: &mut Vec>) { 40 | if start >= nums.len() { 41 | result.push(curr); 42 | return; 43 | } 44 | // current element dropped 45 | Solution::backtrack(start + 1, curr.clone(), nums, result); 46 | // current element picked 47 | curr.push(nums[start]); 48 | Solution::backtrack(start + 1, curr, nums, result); 49 | } 50 | } 51 | 52 | // submission codes end 53 | 54 | #[cfg(test)] 55 | mod tests { 56 | use super::*; 57 | 58 | #[test] 59 | fn test_78() { 60 | assert_eq!(Solution::subsets(vec![]), vec![vec![]]); 61 | assert_eq!(Solution::subsets(vec![1]), vec![vec![], vec![1]]); 62 | assert_eq!( 63 | Solution::subsets(vec![1, 2]), 64 | vec![vec![], vec![2], vec![1], vec![1, 2]] 65 | ); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/solution/s0081_search_in_rotated_sorted_array_ii.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [81] Search in Rotated Sorted Array II 3 | * 4 | * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 5 | * 6 | * (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). 7 | * 8 | * You are given a target value to search. If found in the array return true, otherwise return false. 9 | * 10 | * Example 1: 11 | * 12 | * 13 | * Input: nums = [2,5,6,0,0,1,2], target = 0 14 | * Output: true 15 | * 16 | * 17 | * Example 2: 18 | * 19 | * 20 | * Input: nums = [2,5,6,0,0,1,2], target = 3 21 | * Output: false 22 | * 23 | * Follow up: 24 | * 25 | * 26 | * This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates. 27 | * Would this affect the run-time complexity? How and why? 28 | * 29 | * 30 | */ 31 | pub struct Solution {} 32 | 33 | // problem: https://leetcode.com/problems/search-in-rotated-sorted-array-ii/ 34 | // discuss: https://leetcode.com/problems/search-in-rotated-sorted-array-ii/discuss/?currentPage=1&orderBy=most_votes&query= 35 | 36 | // submission codes start here 37 | 38 | impl Solution { 39 | pub fn search(nums: Vec, target: i32) -> bool { 40 | false 41 | } 42 | } 43 | 44 | // submission codes end 45 | 46 | #[cfg(test)] 47 | mod tests { 48 | use super::*; 49 | 50 | #[test] 51 | fn test_81() {} 52 | } 53 | -------------------------------------------------------------------------------- /src/solution/s0082_remove_duplicates_from_sorted_list_ii.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [82] Remove Duplicates from Sorted List II 3 | * 4 | * Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: 1->2->3->3->4->4->5 10 | * Output: 1->2->5 11 | * 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: 1->1->1->2->3 17 | * Output: 2->3 18 | * 19 | * 20 | */ 21 | pub struct Solution {} 22 | use crate::util::linked_list::{to_list, ListNode}; 23 | 24 | // problem: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ 25 | // discuss: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/discuss/?currentPage=1&orderBy=most_votes&query= 26 | 27 | // submission codes start here 28 | 29 | // Definition for singly-linked list. 30 | // #[derive(PartialEq, Eq, Debug)] 31 | // pub struct ListNode { 32 | // pub val: i32, 33 | // pub next: Option> 34 | // } 35 | // 36 | // impl ListNode { 37 | // #[inline] 38 | // fn new(val: i32) -> Self { 39 | // ListNode { 40 | // next: None, 41 | // val 42 | // } 43 | // } 44 | // } 45 | impl Solution { 46 | pub fn delete_duplicates(head: Option>) -> Option> { 47 | None 48 | } 49 | } 50 | 51 | // submission codes end 52 | 53 | #[cfg(test)] 54 | mod tests { 55 | use super::*; 56 | 57 | #[test] 58 | fn test_82() {} 59 | } 60 | -------------------------------------------------------------------------------- /src/solution/s0083_remove_duplicates_from_sorted_list.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [83] Remove Duplicates from Sorted List 3 | * 4 | * Given a sorted linked list, delete all duplicates such that each element appear only once. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: 1->1->2 10 | * Output: 1->2 11 | * 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: 1->1->2->3->3 17 | * Output: 1->2->3 18 | * 19 | * 20 | */ 21 | pub struct Solution {} 22 | use crate::util::linked_list::{to_list, ListNode}; 23 | 24 | // problem: https://leetcode.com/problems/remove-duplicates-from-sorted-list/ 25 | // discuss: https://leetcode.com/problems/remove-duplicates-from-sorted-list/discuss/?currentPage=1&orderBy=most_votes&query= 26 | 27 | // submission codes start here 28 | 29 | // Definition for singly-linked list. 30 | // #[derive(PartialEq, Eq, Debug)] 31 | // pub struct ListNode { 32 | // pub val: i32, 33 | // pub next: Option> 34 | // } 35 | // 36 | // impl ListNode { 37 | // #[inline] 38 | // fn new(val: i32) -> Self { 39 | // ListNode { 40 | // next: None, 41 | // val 42 | // } 43 | // } 44 | // } 45 | impl Solution { 46 | pub fn delete_duplicates(head: Option>) -> Option> { 47 | None 48 | } 49 | } 50 | 51 | // submission codes end 52 | 53 | #[cfg(test)] 54 | mod tests { 55 | use super::*; 56 | 57 | #[test] 58 | fn test_83() {} 59 | } 60 | -------------------------------------------------------------------------------- /src/solution/s0085_maximal_rectangle.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [85] Maximal Rectangle 3 | * 4 | * Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: 10 | * [ 11 | * ["1","0","1","0","0"], 12 | * ["1","0","1","1","1"], 13 | * ["1","1","1","1","1"], 14 | * ["1","0","0","1","0"] 15 | * ] 16 | * Output: 6 17 | * 18 | * 19 | */ 20 | pub struct Solution {} 21 | 22 | // problem: https://leetcode.com/problems/maximal-rectangle/ 23 | // discuss: https://leetcode.com/problems/maximal-rectangle/discuss/?currentPage=1&orderBy=most_votes&query= 24 | 25 | // submission codes start here 26 | 27 | impl Solution { 28 | pub fn maximal_rectangle(matrix: Vec>) -> i32 { 29 | let mut max_area = 0; 30 | 31 | max_area 32 | } 33 | } 34 | 35 | // submission codes end 36 | 37 | #[cfg(test)] 38 | mod tests { 39 | use super::*; 40 | 41 | #[test] 42 | fn test_85() {} 43 | } 44 | -------------------------------------------------------------------------------- /src/solution/s0086_partition_list.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [86] Partition List 3 | * 4 | * Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 5 | * 6 | * You should preserve the original relative order of the nodes in each of the two partitions. 7 | * 8 | * Example: 9 | * 10 | * 11 | * Input: head = 1->4->3->2->5->2, x = 3 12 | * Output: 1->2->2->4->3->5 13 | * 14 | * 15 | */ 16 | pub struct Solution {} 17 | use crate::util::linked_list::{to_list, ListNode}; 18 | 19 | // problem: https://leetcode.com/problems/partition-list/ 20 | // discuss: https://leetcode.com/problems/partition-list/discuss/?currentPage=1&orderBy=most_votes&query= 21 | 22 | // submission codes start here 23 | 24 | impl Solution { 25 | pub fn partition(head: Option>, x: i32) -> Option> { 26 | let mut lower = Some(Box::new(ListNode::new(0))); 27 | let mut higher = Some(Box::new(ListNode::new(0))); 28 | let mut lower_tail = lower.as_mut(); 29 | let mut higher_tail = higher.as_mut(); 30 | let mut head = head; 31 | while let Some(mut inner) = head { 32 | let mut next = inner.next.take(); 33 | if inner.val < x { 34 | lower_tail.as_mut().unwrap().next = Some(inner); 35 | lower_tail = lower_tail.unwrap().next.as_mut(); 36 | } else { 37 | higher_tail.as_mut().unwrap().next = Some(inner); 38 | higher_tail = higher_tail.unwrap().next.as_mut(); 39 | } 40 | head = next 41 | } 42 | lower_tail.as_mut().unwrap().next = higher.unwrap().next.take(); 43 | lower.unwrap().next.take() 44 | } 45 | } 46 | 47 | // submission codes end 48 | 49 | #[cfg(test)] 50 | mod tests { 51 | use super::*; 52 | 53 | #[test] 54 | fn test_86() { 55 | assert_eq!( 56 | Solution::partition(linked![1, 4, 3, 2, 5, 2], 3), 57 | linked![1, 2, 2, 4, 3, 5] 58 | ); 59 | assert_eq!( 60 | Solution::partition(linked![1, 4, 3, 2, 5, 2], 8), 61 | linked![1, 4, 3, 2, 5, 2] 62 | ); 63 | assert_eq!(Solution::partition(linked![], 0), linked![]); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/solution/s0087_scramble_string.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [87] Scramble String 3 | * 4 | * Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. 5 | * 6 | * Below is one possible representation of s1 = "great": 7 | * 8 | * 9 | * great 10 | * / \ 11 | * gr eat 12 | * / \ / \ 13 | * g r e at 14 | * / \ 15 | * a t 16 | * 17 | * 18 | * To scramble the string, we may choose any non-leaf node and swap its two children. 19 | * 20 | * For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat". 21 | * 22 | * 23 | * rgeat 24 | * / \ 25 | * rg eat 26 | * / \ / \ 27 | * r g e at 28 | * / \ 29 | * a t 30 | * 31 | * 32 | * We say that "rgeat" is a scrambled string of "great". 33 | * 34 | * Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae". 35 | * 36 | * 37 | * rgtae 38 | * / \ 39 | * rg tae 40 | * / \ / \ 41 | * r g ta e 42 | * / \ 43 | * t a 44 | * 45 | * 46 | * We say that "rgtae" is a scrambled string of "great". 47 | * 48 | * Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1. 49 | * 50 | * Example 1: 51 | * 52 | * 53 | * Input: s1 = "great", s2 = "rgeat" 54 | * Output: true 55 | * 56 | * 57 | * Example 2: 58 | * 59 | * 60 | * Input: s1 = "abcde", s2 = "caebd" 61 | * Output: false 62 | * 63 | */ 64 | pub struct Solution {} 65 | 66 | // problem: https://leetcode.com/problems/scramble-string/ 67 | // discuss: https://leetcode.com/problems/scramble-string/discuss/?currentPage=1&orderBy=most_votes&query= 68 | 69 | // submission codes start here 70 | 71 | impl Solution { 72 | pub fn is_scramble(s1: String, s2: String) -> bool { 73 | false 74 | } 75 | } 76 | 77 | // submission codes end 78 | 79 | #[cfg(test)] 80 | mod tests { 81 | use super::*; 82 | 83 | #[test] 84 | fn test_87() {} 85 | } 86 | -------------------------------------------------------------------------------- /src/solution/s0088_merge_sorted_array.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [88] Merge Sorted Array 3 | * 4 | * Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 5 | * 6 | * Note: 7 | * 8 | * 9 | * The number of elements initialized in nums1 and nums2 are m and n respectively. 10 | * You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. 11 | * 12 | * 13 | * Example: 14 | * 15 | * 16 | * Input: 17 | * nums1 = [1,2,3,0,0,0], m = 3 18 | * nums2 = [2,5,6], n = 3 19 | * 20 | * Output: [1,2,2,3,5,6] 21 | * 22 | * 23 | */ 24 | pub struct Solution {} 25 | 26 | // problem: https://leetcode.com/problems/merge-sorted-array/ 27 | // discuss: https://leetcode.com/problems/merge-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= 28 | 29 | // submission codes start here 30 | 31 | impl Solution { 32 | pub fn merge(nums1: &mut Vec, m: i32, nums2: &mut Vec, n: i32) { 33 | let mut i = m - 1; 34 | let mut j = n - 1; 35 | let mut z = m + n - 1; 36 | while z >= 0 { 37 | if i >= 0 && (j < 0 || nums1[i as usize] >= nums2[j as usize]) { 38 | nums1[z as usize] = nums1[i as usize]; 39 | i -= 1; 40 | } else { 41 | nums1[z as usize] = nums2[j as usize]; 42 | j -= 1; 43 | } 44 | z -= 1; 45 | } 46 | } 47 | } 48 | 49 | // submission codes end 50 | 51 | #[cfg(test)] 52 | mod tests { 53 | use super::*; 54 | 55 | #[test] 56 | fn test_88() { 57 | let mut vec1 = vec![1, 2, 3, 0, 0, 0]; 58 | let mut vec2 = vec![2, 5, 6]; 59 | Solution::merge(&mut vec1, 3, &mut vec2, 3); 60 | assert_eq!(vec1, vec![1, 2, 2, 3, 5, 6]); 61 | 62 | let mut vec1 = vec![1, 2, 3]; 63 | let mut vec2 = vec![]; 64 | Solution::merge(&mut vec1, 3, &mut vec2, 0); 65 | assert_eq!(vec1, vec![1, 2, 3]); 66 | 67 | let mut vec1 = vec![0, 0, 0]; 68 | let mut vec2 = vec![1, 2, 3]; 69 | Solution::merge(&mut vec1, 0, &mut vec2, 3); 70 | assert_eq!(vec1, vec![1, 2, 3]); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/solution/s0089_gray_code.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [89] Gray Code 3 | * 4 | * The gray code is a binary numeral system where two successive values differ in only one bit. 5 | * 6 | * Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 7 | * 8 | * Example 1: 9 | * 10 | * 11 | * Input: 2 12 | * Output: [0,1,3,2] 13 | * Explanation: 14 | * 00 - 0 15 | * 01 - 1 16 | * 11 - 3 17 | * 10 - 2 18 | * 19 | * For a given n, a gray code sequence may not be uniquely defined. 20 | * For example, [0,2,3,1] is also a valid gray code sequence. 21 | * 22 | * 00 - 0 23 | * 10 - 2 24 | * 11 - 3 25 | * 01 - 1 26 | * 27 | * 28 | * Example 2: 29 | * 30 | * 31 | * Input: 0 32 | * Output: [0] 33 | * Explanation: We define the gray code sequence to begin with 0. 34 | * A gray code sequence of n has size = 2^n, which for n = 0 the size is 2^0 = 1. 35 | * Therefore, for n = 0 the gray code sequence is [0]. 36 | * 37 | * 38 | */ 39 | pub struct Solution {} 40 | 41 | // problem: https://leetcode.com/problems/gray-code/ 42 | // discuss: https://leetcode.com/problems/gray-code/discuss/?currentPage=1&orderBy=most_votes&query= 43 | 44 | // submission codes start here 45 | 46 | /* 47 | 0000 48 | 0001 <- flip [0] to 1, traverse [] in reverse order 49 | 0011 <- flip [1] to 1, traverse [0] in reverse order 50 | 0010 51 | 0110 <- flip [2] to 1, traverse [1,0] in reverse order 52 | 0111 53 | 0101 54 | 0100 55 | 1100 <- flip [3] to 1, traverse [2,1,0] in reverse order 56 | */ 57 | impl Solution { 58 | pub fn gray_code(n: i32) -> Vec { 59 | let mut res = vec![0]; 60 | for i in 0..n { 61 | for j in (0..res.len()).rev() { 62 | res.push(2_i32.pow(i as u32) + res[j]); 63 | } 64 | } 65 | res 66 | } 67 | } 68 | 69 | // submission codes end 70 | 71 | #[cfg(test)] 72 | mod tests { 73 | use super::*; 74 | 75 | #[test] 76 | fn test_89() { 77 | assert_eq!(Solution::gray_code(2), vec![0, 1, 3, 2]); 78 | assert_eq!(Solution::gray_code(1), vec![0, 1]); 79 | assert_eq!(Solution::gray_code(0), vec![0]); 80 | assert_eq!(Solution::gray_code(3), vec![0, 1, 3, 2, 6, 7, 5, 4]); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/solution/s0091_decode_ways.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [91] Decode Ways 3 | * 4 | * A message containing letters from A-Z is being encoded to numbers using the following mapping: 5 | * 6 | * 7 | * 'A' -> 1 8 | * 'B' -> 2 9 | * ... 10 | * 'Z' -> 26 11 | * 12 | * 13 | * Given a non-empty string containing only digits, determine the total number of ways to decode it. 14 | * 15 | * Example 1: 16 | * 17 | * 18 | * Input: "12" 19 | * Output: 2 20 | * Explanation: It could be decoded as "AB" (1 2) or "L" (12). 21 | * 22 | * 23 | * Example 2: 24 | * 25 | * 26 | * Input: "226" 27 | * Output: 3 28 | * Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). 29 | * 30 | */ 31 | pub struct Solution {} 32 | 33 | // problem: https://leetcode.com/problems/decode-ways/ 34 | // discuss: https://leetcode.com/problems/decode-ways/discuss/?currentPage=1&orderBy=most_votes&query= 35 | 36 | // submission codes start here 37 | 38 | impl Solution { 39 | pub fn num_decodings(s: String) -> i32 { 40 | 0 41 | } 42 | } 43 | 44 | // submission codes end 45 | 46 | #[cfg(test)] 47 | mod tests { 48 | use super::*; 49 | 50 | #[test] 51 | fn test_91() {} 52 | } 53 | -------------------------------------------------------------------------------- /src/solution/s0092_reverse_linked_list_ii.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [92] Reverse Linked List II 3 | * 4 | * Reverse a linked list from position m to n. Do it in one-pass. 5 | * 6 | * Note: 1 ≤ m ≤ n ≤ length of list. 7 | * 8 | * Example: 9 | * 10 | * 11 | * Input: 1->2->3->4->5->NULL, m = 2, n = 4 12 | * Output: 1->4->3->2->5->NULL 13 | * 14 | * 15 | */ 16 | pub struct Solution {} 17 | use crate::util::linked_list::{to_list, ListNode}; 18 | 19 | // problem: https://leetcode.com/problems/reverse-linked-list-ii/ 20 | // discuss: https://leetcode.com/problems/reverse-linked-list-ii/discuss/?currentPage=1&orderBy=most_votes&query= 21 | 22 | // submission codes start here 23 | 24 | // Definition for singly-linked list. 25 | // #[derive(PartialEq, Eq, Debug)] 26 | // pub struct ListNode { 27 | // pub val: i32, 28 | // pub next: Option> 29 | // } 30 | // 31 | // impl ListNode { 32 | // #[inline] 33 | // fn new(val: i32) -> Self { 34 | // ListNode { 35 | // next: None, 36 | // val 37 | // } 38 | // } 39 | // } 40 | impl Solution { 41 | pub fn reverse_between(head: Option>, m: i32, n: i32) -> Option> { 42 | None 43 | } 44 | } 45 | 46 | // submission codes end 47 | 48 | #[cfg(test)] 49 | mod tests { 50 | use super::*; 51 | 52 | #[test] 53 | fn test_92() {} 54 | } 55 | -------------------------------------------------------------------------------- /src/solution/s0093_restore_ip_addresses.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [93] Restore IP Addresses 3 | * 4 | * Given a string containing only digits, restore it by returning all possible valid IP address combinations. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: "25525511135" 10 | * Output: ["255.255.11.135", "255.255.111.35"] 11 | * 12 | * 13 | */ 14 | pub struct Solution {} 15 | 16 | // problem: https://leetcode.com/problems/restore-ip-addresses/ 17 | // discuss: https://leetcode.com/problems/restore-ip-addresses/discuss/?currentPage=1&orderBy=most_votes&query= 18 | 19 | // submission codes start here 20 | 21 | impl Solution { 22 | pub fn restore_ip_addresses(s: String) -> Vec { 23 | vec![] 24 | } 25 | } 26 | 27 | // submission codes end 28 | 29 | #[cfg(test)] 30 | mod tests { 31 | use super::*; 32 | 33 | #[test] 34 | fn test_93() {} 35 | } 36 | -------------------------------------------------------------------------------- /src/solution/s0094_binary_tree_inorder_traversal.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [94] Binary Tree Inorder Traversal 3 | * 4 | * Given a binary tree, return the inorder traversal of its nodes' values. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: [1,null,2,3] 10 | * 1 11 | * \ 12 | * 2 13 | * / 14 | * 3 15 | * 16 | * Output: [1,3,2] 17 | * 18 | * Follow up: Recursive solution is trivial, could you do it iteratively? 19 | * 20 | */ 21 | pub struct Solution {} 22 | 23 | // problem: https://leetcode.com/problems/binary-tree-inorder-traversal/ 24 | // discuss: https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= 25 | 26 | // submission codes start here 27 | 28 | use crate::util::tree::{to_tree, TreeNode}; 29 | use std::cell::RefCell; 30 | use std::rc::Rc; 31 | impl Solution { 32 | pub fn inorder_traversal(root: Option>>) -> Vec { 33 | let mut res = Vec::new(); 34 | Solution::inorder_traverse(root.as_ref(), &mut (|v| res.push(v))); 35 | res 36 | } 37 | 38 | fn inorder_traverse(root: Option<&Rc>>, consumer: &mut F) { 39 | if let Some(node) = root { 40 | Solution::inorder_traverse(node.borrow().left.as_ref(), consumer); 41 | consumer(root.as_ref().unwrap().borrow().val); 42 | Solution::inorder_traverse(node.borrow().right.as_ref(), consumer); 43 | } 44 | } 45 | } 46 | 47 | // submission codes end 48 | 49 | #[cfg(test)] 50 | mod tests { 51 | use super::*; 52 | 53 | #[test] 54 | fn test_94() { 55 | assert_eq!( 56 | Solution::inorder_traversal(tree![1, null, 2, 3]), 57 | vec![1, 3, 2] 58 | ); 59 | assert_eq!( 60 | Solution::inorder_traversal(tree![1, 2, 3, 4, 5, 6, 7]), 61 | vec![4, 2, 5, 1, 6, 3, 7] 62 | ); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/solution/s0096_unique_binary_search_trees.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [96] Unique Binary Search Trees 3 | * 4 | * Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: 3 10 | * Output: 5 11 | * Explanation: 12 | * Given n = 3, there are a total of 5 unique BST's: 13 | * 14 | * 1 3 3 2 1 15 | * \ / / / \ \ 16 | * 3 2 1 1 3 2 17 | * / / \ \ 18 | * 2 1 2 3 19 | * 20 | * 21 | */ 22 | pub struct Solution {} 23 | 24 | // problem: https://leetcode.com/problems/unique-binary-search-trees/ 25 | // discuss: https://leetcode.com/problems/unique-binary-search-trees/discuss/?currentPage=1&orderBy=most_votes&query= 26 | 27 | // submission codes start here 28 | 29 | impl Solution { 30 | pub fn num_trees(n: i32) -> i32 { 31 | 0 32 | } 33 | } 34 | 35 | // submission codes end 36 | 37 | #[cfg(test)] 38 | mod tests { 39 | use super::*; 40 | 41 | #[test] 42 | fn test_96() {} 43 | } 44 | -------------------------------------------------------------------------------- /src/solution/s0100_same_tree.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [100] Same Tree 3 | * 4 | * Given two binary trees, write a function to check if they are the same or not. 5 | * 6 | * Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 7 | * 8 | * Example 1: 9 | * 10 | * 11 | * Input: 1 1 12 | * / \ / \ 13 | * 2 3 2 3 14 | * 15 | * [1,2,3], [1,2,3] 16 | * 17 | * Output: true 18 | * 19 | * 20 | * Example 2: 21 | * 22 | * 23 | * Input: 1 1 24 | * / \ 25 | * 2 2 26 | * 27 | * [1,2], [1,null,2] 28 | * 29 | * Output: false 30 | * 31 | * 32 | * Example 3: 33 | * 34 | * 35 | * Input: 1 1 36 | * / \ / \ 37 | * 2 1 1 2 38 | * 39 | * [1,2,1], [1,1,2] 40 | * 41 | * Output: false 42 | * 43 | * 44 | */ 45 | pub struct Solution {} 46 | 47 | use crate::util::tree::{to_tree, TreeNode}; 48 | // problem: https://leetcode.com/problems/same-tree/ 49 | // discuss: https://leetcode.com/problems/same-tree/discuss/?currentPage=1&orderBy=most_votes&query= 50 | 51 | // submission codes start here 52 | use std::cell::RefCell; 53 | use std::rc::Rc; 54 | impl Solution { 55 | pub fn is_same_tree( 56 | p: Option>>, 57 | q: Option>>, 58 | ) -> bool { 59 | p == q 60 | } 61 | } 62 | 63 | // submission codes end 64 | 65 | #[cfg(test)] 66 | mod tests { 67 | use super::*; 68 | 69 | #[test] 70 | fn test_100() { 71 | assert_eq!( 72 | Solution::is_same_tree(tree![1, 2, 3, 4, null, 5], tree![1, 2, 3, 4, null, 5]), 73 | true 74 | ) 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/solution/s0102_binary_tree_level_order_traversal.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [102] Binary Tree Level Order Traversal 3 | * 4 | * Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 5 | * 6 | * 7 | * For example:
8 | * Given binary tree [3,9,20,null,null,15,7],
9 | * 10 | * 3 11 | * / \ 12 | * 9 20 13 | * / \ 14 | * 15 7 15 | * 16 | * 17 | * 18 | * return its level order traversal as:
19 | * 20 | * [ 21 | * [3], 22 | * [9,20], 23 | * [15,7] 24 | * ] 25 | * 26 | * 27 | */ 28 | pub struct Solution {} 29 | use crate::util::tree::{to_tree, TreeNode}; 30 | 31 | // problem: https://leetcode.com/problems/binary-tree-level-order-traversal/ 32 | // discuss: https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/?currentPage=1&orderBy=most_votes&query= 33 | 34 | // submission codes start here 35 | 36 | use std::cell::RefCell; 37 | use std::collections::VecDeque; 38 | use std::rc::Rc; 39 | impl Solution { 40 | pub fn level_order(root: Option>>) -> Vec> { 41 | let mut res = Vec::new(); 42 | let mut current_level = 0; 43 | if root.is_none() { 44 | return res; 45 | } 46 | let mut deq = VecDeque::new(); 47 | deq.push_back((0, root.clone())); 48 | let mut vec = Vec::new(); 49 | while !deq.is_empty() { 50 | if let Some((level, Some(node))) = deq.pop_front() { 51 | deq.push_back((level + 1, node.borrow().left.clone())); 52 | deq.push_back((level + 1, node.borrow().right.clone())); 53 | if level > current_level { 54 | res.push(vec); 55 | vec = Vec::new(); 56 | current_level = level; 57 | } 58 | vec.push(node.borrow().val); 59 | } 60 | } 61 | if !vec.is_empty() { 62 | res.push(vec) 63 | } 64 | res 65 | } 66 | } 67 | 68 | // submission codes end 69 | 70 | #[cfg(test)] 71 | mod tests { 72 | use super::*; 73 | 74 | #[test] 75 | fn test_102() { 76 | assert_eq!( 77 | Solution::level_order(tree![3, 9, 20, null, null, 15, 7]), 78 | vec![vec![3], vec![9, 20], vec![15, 7]] 79 | ); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/solution/s0104_maximum_depth_of_binary_tree.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [104] Maximum Depth of Binary Tree 3 | * 4 | * Given a binary tree, find its maximum depth. 5 | * 6 | * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 7 | * 8 | * Note: A leaf is a node with no children. 9 | * 10 | * Example: 11 | * 12 | * Given binary tree [3,9,20,null,null,15,7], 13 | * 14 | * 15 | * 3 16 | * / \ 17 | * 9 20 18 | * / \ 19 | * 15 7 20 | * 21 | * return its depth = 3. 22 | * 23 | */ 24 | pub struct Solution {} 25 | use crate::util::tree::{to_tree, TreeNode}; 26 | 27 | // problem: https://leetcode.com/problems/maximum-depth-of-binary-tree/ 28 | // discuss: https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= 29 | 30 | // submission codes start here 31 | 32 | use std::cell::RefCell; 33 | use std::rc::Rc; 34 | impl Solution { 35 | pub fn max_depth(root: Option>>) -> i32 { 36 | let mut max = 0; 37 | Solution::depth_helper(root.as_ref(), &mut max, 0); 38 | max 39 | } 40 | 41 | fn depth_helper(root: Option<&Rc>>, max: &mut i32, curr: i32) { 42 | if let Some(node) = root { 43 | *max = i32::max(*max, curr + 1); 44 | Solution::depth_helper(node.borrow().left.as_ref(), max, curr + 1); 45 | Solution::depth_helper(node.borrow().right.as_ref(), max, curr + 1); 46 | } 47 | } 48 | } 49 | 50 | // submission codes end 51 | 52 | #[cfg(test)] 53 | mod tests { 54 | use super::*; 55 | 56 | #[test] 57 | fn test_104() { 58 | assert_eq!(Solution::max_depth(tree![]), 0); 59 | assert_eq!(Solution::max_depth(tree![3, 9, 20, null, null, 15, 7]), 3); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/solution/s0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [105] Construct Binary Tree from Preorder and Inorder Traversal 3 | * 4 | * Given preorder and inorder traversal of a tree, construct the binary tree. 5 | * 6 | * Note:
7 | * You may assume that duplicates do not exist in the tree. 8 | * 9 | * For example, given 10 | * 11 | * 12 | * preorder = [3,9,20,15,7] 13 | * inorder = [9,3,15,20,7] 14 | * 15 | * Return the following binary tree: 16 | * 17 | * 18 | * 3 19 | * / \ 20 | * 9 20 21 | * / \ 22 | * 15 7 23 | * 24 | */ 25 | pub struct Solution {} 26 | use crate::util::tree::{to_tree, TreeNode}; 27 | 28 | // problem: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ 29 | // discuss: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= 30 | 31 | // submission codes start here 32 | 33 | use std::cell::RefCell; 34 | use std::rc::Rc; 35 | impl Solution { 36 | pub fn build_tree(preorder: Vec, inorder: Vec) -> Option>> { 37 | Solution::build_tree_helper(&preorder[..], &inorder[..]) 38 | } 39 | 40 | fn build_tree_helper(preorder: &[i32], inorder: &[i32]) -> Option>> { 41 | if preorder.is_empty() { 42 | return None; 43 | } 44 | let root_idx = inorder.iter().position(|&v| v == preorder[0]).unwrap(); 45 | Some(Rc::new(RefCell::new(TreeNode { 46 | val: preorder[0], 47 | left: Solution::build_tree_helper(&preorder[1..root_idx + 1], &inorder[0..root_idx]), 48 | right: Solution::build_tree_helper(&preorder[root_idx + 1..], &inorder[root_idx + 1..]), 49 | }))) 50 | } 51 | } 52 | 53 | // submission codes end 54 | 55 | #[cfg(test)] 56 | mod tests { 57 | use super::*; 58 | 59 | #[test] 60 | fn test_105() { 61 | assert_eq!( 62 | Solution::build_tree(vec![3, 9, 20, 15, 7], vec![9, 3, 15, 20, 7]), 63 | tree![3, 9, 20, null, null, 15, 7] 64 | ); 65 | assert_eq!( 66 | Solution::build_tree(vec![3, 20, 7], vec![3, 20, 7]), 67 | tree![3, null, 20, null, 7] 68 | ); 69 | assert_eq!(Solution::build_tree(vec![], vec![]), tree![]); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/solution/s0108_convert_sorted_array_to_binary_search_tree.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [108] Convert Sorted Array to Binary Search Tree 3 | * 4 | * Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 5 | * 6 | * For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 7 | * 8 | * Example: 9 | * 10 | * 11 | * Given the sorted array: [-10,-3,0,5,9], 12 | * 13 | * One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 14 | * 15 | * 0 16 | * / \ 17 | * -3 9 18 | * / / 19 | * -10 5 20 | * 21 | * 22 | */ 23 | pub struct Solution {} 24 | use crate::util::tree::{to_tree, TreeNode}; 25 | 26 | // problem: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 27 | // discuss: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= 28 | 29 | // submission codes start here 30 | 31 | use std::cell::RefCell; 32 | use std::rc::Rc; 33 | impl Solution { 34 | pub fn sorted_array_to_bst(nums: Vec) -> Option>> { 35 | Solution::bst_helper(&nums[..]) 36 | } 37 | 38 | fn bst_helper(nums: &[i32]) -> Option>> { 39 | if nums.is_empty() { 40 | return None; 41 | } 42 | Some(Rc::new(RefCell::new(TreeNode { 43 | val: nums[nums.len() / 2], 44 | left: Solution::bst_helper(&nums[0..(nums.len() / 2)]), 45 | right: Solution::bst_helper(&nums[(nums.len() / 2 + 1)..]), 46 | }))) 47 | } 48 | } 49 | 50 | // submission codes end 51 | 52 | #[cfg(test)] 53 | mod tests { 54 | use super::*; 55 | 56 | #[test] 57 | fn test_108() { 58 | assert_eq!( 59 | Solution::sorted_array_to_bst(vec![-10, -3, 0, 5, 9]), 60 | tree![0, -3, 9, -10, null, 5] 61 | ); 62 | assert_eq!(Solution::sorted_array_to_bst(vec![]), tree![]); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/solution/s0109_convert_sorted_list_to_binary_search_tree.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [109] Convert Sorted List to Binary Search Tree 3 | * 4 | * Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 5 | * 6 | * For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 7 | * 8 | * Example: 9 | * 10 | * 11 | * Given the sorted linked list: [-10,-3,0,5,9], 12 | * 13 | * One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 14 | * 15 | * 0 16 | * / \ 17 | * -3 9 18 | * / / 19 | * -10 5 20 | * 21 | * 22 | */ 23 | pub struct Solution {} 24 | use crate::util::linked_list::{to_list, ListNode}; 25 | use crate::util::tree::{to_tree, TreeNode}; 26 | 27 | // problem: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ 28 | // discuss: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= 29 | 30 | // submission codes start here 31 | 32 | use std::cell::RefCell; 33 | use std::rc::Rc; 34 | impl Solution { 35 | pub fn sorted_list_to_bst(head: Option>) -> Option>> { 36 | let mut arr = Vec::new(); 37 | let mut head = head; 38 | while let Some(node) = head { 39 | arr.push(node.val); 40 | head = node.next; 41 | } 42 | Solution::bst_helper(&arr[..]) 43 | } 44 | 45 | fn bst_helper(nums: &[i32]) -> Option>> { 46 | if nums.is_empty() { 47 | return None; 48 | } 49 | Some(Rc::new(RefCell::new(TreeNode { 50 | val: nums[nums.len() / 2], 51 | left: Solution::bst_helper(&nums[0..(nums.len() / 2)]), 52 | right: Solution::bst_helper(&nums[(nums.len() / 2 + 1)..]), 53 | }))) 54 | } 55 | } 56 | 57 | // submission codes end 58 | 59 | #[cfg(test)] 60 | mod tests { 61 | use super::*; 62 | 63 | #[test] 64 | fn test_109() { 65 | assert_eq!( 66 | Solution::sorted_list_to_bst(linked![-10, -3, 0, 5, 9]), 67 | tree![0, -3, 9, -10, null, 5] 68 | ); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/solution/s0111_minimum_depth_of_binary_tree.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [111] Minimum Depth of Binary Tree 3 | * 4 | * Given a binary tree, find its minimum depth. 5 | * 6 | * The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 7 | * 8 | * Note: A leaf is a node with no children. 9 | * 10 | * Example: 11 | * 12 | * Given binary tree [3,9,20,null,null,15,7], 13 | * 14 | * 15 | * 3 16 | * / \ 17 | * 9 20 18 | * / \ 19 | * 15 7 20 | * 21 | * return its minimum depth = 2. 22 | * 23 | */ 24 | pub struct Solution {} 25 | use crate::util::tree::{to_tree, TreeNode}; 26 | 27 | // problem: https://leetcode.com/problems/minimum-depth-of-binary-tree/ 28 | // discuss: https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= 29 | 30 | // submission codes start here 31 | 32 | use std::cell::RefCell; 33 | use std::collections::VecDeque; 34 | use std::rc::Rc; 35 | impl Solution { 36 | pub fn min_depth(root: Option>>) -> i32 { 37 | if root.is_none() { 38 | return 0; 39 | } 40 | let mut deq = VecDeque::new(); 41 | deq.push_back((1, root.clone())); 42 | while !deq.is_empty() { 43 | if let Some((level, Some(node))) = deq.pop_front() { 44 | if node.borrow().left.is_none() && node.borrow().right.is_none() { 45 | return level; 46 | } 47 | deq.push_back((level + 1, node.borrow().left.clone())); 48 | deq.push_back((level + 1, node.borrow().right.clone())); 49 | } 50 | } 51 | 0 52 | } 53 | } 54 | 55 | // submission codes end 56 | 57 | #[cfg(test)] 58 | mod tests { 59 | use super::*; 60 | 61 | #[test] 62 | fn test_111() { 63 | assert_eq!(Solution::min_depth(tree![3, 9, 20, null, null, 15, 7]), 2); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/solution/s0118_pascals_triangle.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [118] Pascal's Triangle 3 | * 4 | * Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. 5 | * 6 | *
7 | * In Pascal's triangle, each number is the sum of the two numbers directly above it. 8 | * 9 | * Example: 10 | * 11 | * 12 | * Input: 5 13 | * Output: 14 | * [ 15 | * [1], 16 | * [1,1], 17 | * [1,2,1], 18 | * [1,3,3,1], 19 | * [1,4,6,4,1] 20 | * ] 21 | * 22 | * 23 | */ 24 | pub struct Solution {} 25 | 26 | // problem: https://leetcode.com/problems/pascals-triangle/ 27 | // discuss: https://leetcode.com/problems/pascals-triangle/discuss/?currentPage=1&orderBy=most_votes&query= 28 | 29 | // submission codes start here 30 | 31 | impl Solution { 32 | pub fn generate(num_rows: i32) -> Vec> { 33 | let mut res = Vec::new(); 34 | if num_rows < 1 { 35 | return res; 36 | } 37 | let mut curr = vec![1]; 38 | for _ in 0..num_rows { 39 | let mut next = vec![1; curr.len() + 1]; 40 | for i in 1..curr.len() { 41 | next[i] = curr[i - 1] + curr[i]; 42 | } 43 | res.push(curr); 44 | curr = next; 45 | } 46 | res 47 | } 48 | } 49 | 50 | // submission codes end 51 | 52 | #[cfg(test)] 53 | mod tests { 54 | use super::*; 55 | 56 | #[test] 57 | fn test_118() { 58 | assert_eq!(Solution::generate(1), vec![vec![1]]); 59 | assert_eq!( 60 | Solution::generate(5), 61 | vec![ 62 | vec![1], 63 | vec![1, 1], 64 | vec![1, 2, 1], 65 | vec![1, 3, 3, 1], 66 | vec![1, 4, 6, 4, 1] 67 | ] 68 | ); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/solution/s0119_pascals_triangle_ii.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [119] Pascal's Triangle II 3 | * 4 | * Given a non-negative index k where k ≤ 33, return the k^th index row of the Pascal's triangle. 5 | * 6 | * Note that the row index starts from 0. 7 | * 8 | *
9 | * In Pascal's triangle, each number is the sum of the two numbers directly above it. 10 | * 11 | * Example: 12 | * 13 | * 14 | * Input: 3 15 | * Output: [1,3,3,1] 16 | * 17 | * 18 | * Follow up: 19 | * 20 | * Could you optimize your algorithm to use only O(k) extra space? 21 | * 22 | */ 23 | pub struct Solution {} 24 | 25 | // problem: https://leetcode.com/problems/pascals-triangle-ii/ 26 | // discuss: https://leetcode.com/problems/pascals-triangle-ii/discuss/?currentPage=1&orderBy=most_votes&query= 27 | 28 | // submission codes start here 29 | 30 | /* 31 | in-place algorithm 32 | 33 | 1 1 1 1 1 34 | 1 2 1 1 1 35 | 1 3 3 1 1 36 | 1 4 6 4 1 37 | */ 38 | impl Solution { 39 | pub fn get_row(row_index: i32) -> Vec { 40 | let mut curr = vec![1; (row_index + 1) as usize]; 41 | for i in 0..row_index + 1 { 42 | let mut prev = 1; 43 | for j in 1..i { 44 | let temp = curr[j as usize]; 45 | curr[j as usize] = temp + prev; 46 | prev = temp; 47 | } 48 | } 49 | curr 50 | } 51 | } 52 | 53 | // submission codes end 54 | 55 | #[cfg(test)] 56 | mod tests { 57 | use super::*; 58 | 59 | #[test] 60 | fn test_119() { 61 | assert_eq!(Solution::get_row(0), vec![1]); 62 | assert_eq!(Solution::get_row(4), vec![1, 4, 6, 4, 1]) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/solution/s0120_triangle.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [120] Triangle 3 | * 4 | * Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 5 | * 6 | * For example, given the following triangle 7 | * 8 | * 9 | * [ 10 | * [2], 11 | * [3,4], 12 | * [6,5,7], 13 | * [4,1,8,3] 14 | * ] 15 | * 16 | * 17 | * The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 18 | * 19 | * Note: 20 | * 21 | * Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. 22 | * 23 | */ 24 | pub struct Solution {} 25 | 26 | // problem: https://leetcode.com/problems/triangle/ 27 | // discuss: https://leetcode.com/problems/triangle/discuss/?currentPage=1&orderBy=most_votes&query= 28 | 29 | // submission codes start here 30 | 31 | impl Solution { 32 | pub fn minimum_total(triangle: Vec>) -> i32 { 33 | let mut cache = vec![0; triangle.len()]; 34 | for row in triangle.iter() { 35 | let mut prev = 0; 36 | for i in 0..row.len() { 37 | let temp = cache[i]; 38 | cache[i] = if i == 0 { 39 | cache[i] 40 | } else if i == row.len() - 1 { 41 | prev 42 | } else { 43 | i32::min(cache[i], prev) 44 | } + row[i]; 45 | prev = temp; 46 | } 47 | } 48 | cache 49 | .into_iter() 50 | .fold(i32::max_value(), |min, x| i32::min(min, x)) 51 | } 52 | } 53 | 54 | // submission codes end 55 | 56 | #[cfg(test)] 57 | mod tests { 58 | use super::*; 59 | 60 | #[test] 61 | fn test_120() { 62 | assert_eq!( 63 | Solution::minimum_total(vec![vec![2], vec![3, 4], vec![6, 5, 7], vec![4, 1, 8, 3]]), 64 | 11 65 | ) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/solution/s0121_best_time_to_buy_and_sell_stock.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [121] Best Time to Buy and Sell Stock 3 | * 4 | * Say you have an array for which the i^th element is the price of a given stock on day i. 5 | * 6 | * If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. 7 | * 8 | * Note that you cannot sell a stock before you buy one. 9 | * 10 | * Example 1: 11 | * 12 | * 13 | * Input: [7,1,5,3,6,4] 14 | * Output: 5 15 | * Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 16 | * Not 7-1 = 6, as selling price needs to be larger than buying price. 17 | * 18 | * 19 | * Example 2: 20 | * 21 | * 22 | * Input: [7,6,4,3,1] 23 | * Output: 0 24 | * Explanation: In this case, no transaction is done, i.e. max profit = 0. 25 | * 26 | * 27 | */ 28 | pub struct Solution {} 29 | 30 | // problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 31 | // discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/?currentPage=1&orderBy=most_votes&query= 32 | 33 | // submission codes start here 34 | 35 | impl Solution { 36 | pub fn max_profit(prices: Vec) -> i32 { 37 | let mut max = 0; 38 | let mut curr = 0; 39 | for i in 1..prices.len() { 40 | curr = curr + prices[i] - prices[i - 1]; 41 | if curr <= 0 { 42 | curr = 0; 43 | } else { 44 | max = i32::max(max, curr); 45 | } 46 | } 47 | max 48 | } 49 | } 50 | 51 | // submission codes end 52 | 53 | #[cfg(test)] 54 | mod tests { 55 | use super::*; 56 | 57 | #[test] 58 | fn test_121() { 59 | assert_eq!(Solution::max_profit(vec![7, 1, 5, 3, 6, 4]), 5); 60 | assert_eq!(Solution::max_profit(vec![7, 6, 4, 3, 1]), 0); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/solution/s0122_best_time_to_buy_and_sell_stock_ii.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [122] Best Time to Buy and Sell Stock II 3 | * 4 | * Say you have an array for which the i^th element is the price of a given stock on day i. 5 | * 6 | * Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). 7 | * 8 | * Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). 9 | * 10 | * Example 1: 11 | * 12 | * 13 | * Input: [7,1,5,3,6,4] 14 | * Output: 7 15 | * Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. 16 | * Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. 17 | * 18 | * 19 | * Example 2: 20 | * 21 | * 22 | * Input: [1,2,3,4,5] 23 | * Output: 4 24 | * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. 25 | * Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are 26 | * engaging multiple transactions at the same time. You must sell before buying again. 27 | * 28 | * 29 | * Example 3: 30 | * 31 | * 32 | * Input: [7,6,4,3,1] 33 | * Output: 0 34 | * Explanation: In this case, no transaction is done, i.e. max profit = 0. 35 | * 36 | */ 37 | pub struct Solution {} 38 | 39 | // problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 40 | // discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/?currentPage=1&orderBy=most_votes&query= 41 | 42 | // submission codes start here 43 | 44 | impl Solution { 45 | pub fn max_profit(prices: Vec) -> i32 { 46 | let mut max = 0; 47 | for i in 1..prices.len() { 48 | if prices[i] > prices[i - 1] { 49 | max += prices[i] - prices[i - 1]; 50 | } 51 | } 52 | max 53 | } 54 | } 55 | 56 | // submission codes end 57 | 58 | #[cfg(test)] 59 | mod tests { 60 | use super::*; 61 | 62 | #[test] 63 | fn test_122() { 64 | assert_eq!(Solution::max_profit(vec![7, 1, 5, 3, 6, 4]), 7); 65 | assert_eq!(Solution::max_profit(vec![1, 2, 3, 4, 5]), 4); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/solution/s0125_valid_palindrome.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [125] Valid Palindrome 3 | * 4 | * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 5 | * 6 | * Note: For the purpose of this problem, we define empty string as valid palindrome. 7 | * 8 | * Example 1: 9 | * 10 | * 11 | * Input: "A man, a plan, a canal: Panama" 12 | * Output: true 13 | * 14 | * 15 | * Example 2: 16 | * 17 | * 18 | * Input: "race a car" 19 | * Output: false 20 | * 21 | * 22 | */ 23 | pub struct Solution {} 24 | 25 | // problem: https://leetcode.com/problems/valid-palindrome/ 26 | // discuss: https://leetcode.com/problems/valid-palindrome/discuss/?currentPage=1&orderBy=most_votes&query= 27 | 28 | // submission codes start here 29 | 30 | impl Solution { 31 | pub fn is_palindrome(s: String) -> bool { 32 | if s.is_empty() { 33 | return true; 34 | } 35 | let seq = s.chars().collect::>(); 36 | let (mut i, mut j) = (0_usize, seq.len() - 1); 37 | while i < j { 38 | while i < seq.len() && !seq[i].is_ascii_alphanumeric() { 39 | i += 1; 40 | } 41 | while j > 0 && !seq[j].is_ascii_alphanumeric() { 42 | j -= 1; 43 | } 44 | if i >= j { 45 | break; 46 | } 47 | if seq[i].to_ascii_lowercase() != seq[j].to_ascii_lowercase() { 48 | return false; 49 | } 50 | i += 1; 51 | j -= 1; 52 | } 53 | true 54 | } 55 | } 56 | 57 | // submission codes end 58 | 59 | #[cfg(test)] 60 | mod tests { 61 | use super::*; 62 | 63 | #[test] 64 | fn test_125() { 65 | assert_eq!( 66 | Solution::is_palindrome("A man, a plan, a canal: Panama".to_owned()), 67 | true 68 | ); 69 | assert_eq!(Solution::is_palindrome("race a car".to_owned()), false); 70 | assert_eq!(Solution::is_palindrome("0P".to_owned()), false); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/solution/s0128_longest_consecutive_sequence.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [128] Longest Consecutive Sequence 3 | * 4 | * Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 5 | * 6 | * Your algorithm should run in O(n) complexity. 7 | * 8 | * Example: 9 | * 10 | * 11 | * Input: [100, 4, 200, 1, 3, 2] 12 | * Output: 4 13 | * Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. 14 | * 15 | * 16 | */ 17 | pub struct Solution {} 18 | 19 | // problem: https://leetcode.com/problems/longest-consecutive-sequence/ 20 | // discuss: https://leetcode.com/problems/longest-consecutive-sequence/discuss/?currentPage=1&orderBy=most_votes&query= 21 | 22 | // submission codes start here 23 | 24 | /* 25 | 要找到连续子串, 基本策略就是对每个 num, 判断 num+1, num+2, num+3... 是否在数组中, 直到不再连续 26 | 27 | 工程里写的话用排序是最清晰可维护的(需求变了很好改), 排序之后查找 num+1 是否存在就只需要 O(1) 的复杂度了: 28 | 看下一个元素是不是 num+1 即可 29 | 30 | 但题目一定要求 O(N) 的解法, 只能想些奇怪的办法了, HashSet 也能达到 O(1) 的查找效率. 但假如对每个元素 31 | 都做一遍, 最差就是 O(N^2) 了, 可以发现对于一个连续序列 1,2,3,4,5,6 我们从 1 开始查就能找到这个序列, 32 | 从 2,3,4,5,6 开始查都是在做重复计算, 因此对于一个 num, 假如 num-1 存在于 HashSet 中, 我们就不需要考虑 33 | 它了, 因为它是一次重复的计算. 34 | */ 35 | use std::collections::HashSet; 36 | impl Solution { 37 | pub fn longest_consecutive(nums: Vec) -> i32 { 38 | let mut max = 0; 39 | let nums = nums.into_iter().collect::>(); 40 | for &num in nums.iter() { 41 | if !nums.contains(&(num - 1)) { 42 | let mut curr = num; 43 | let mut curr_max = 1; 44 | while nums.contains(&(curr + 1)) { 45 | curr += 1; 46 | curr_max += 1; 47 | } 48 | max = i32::max(curr_max, max); 49 | } 50 | } 51 | max 52 | } 53 | } 54 | 55 | // submission codes end 56 | 57 | #[cfg(test)] 58 | mod tests { 59 | use super::*; 60 | 61 | #[test] 62 | fn test_128() { 63 | assert_eq!(Solution::longest_consecutive(vec![100, 4, 200, 1, 3, 2]), 4) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/solution/s0136_single_number.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [136] Single Number 3 | * 4 | * Given a non-empty array of integers, every element appears twice except for one. Find that single one. 5 | * 6 | * Note: 7 | * 8 | * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 9 | * 10 | * Example 1: 11 | * 12 | * 13 | * Input: [2,2,1] 14 | * Output: 1 15 | * 16 | * 17 | * Example 2: 18 | * 19 | * 20 | * Input: [4,1,2,1,2] 21 | * Output: 4 22 | * 23 | * 24 | */ 25 | pub struct Solution {} 26 | 27 | // problem: https://leetcode.com/problems/single-number/ 28 | // discuss: https://leetcode.com/problems/single-number/discuss/?currentPage=1&orderBy=most_votes&query= 29 | 30 | // submission codes start here 31 | impl Solution { 32 | pub fn single_number(nums: Vec) -> i32 { 33 | nums.iter().fold(0, |acc, &num| acc ^ num) 34 | } 35 | } 36 | 37 | // submission codes end 38 | 39 | #[cfg(test)] 40 | mod tests { 41 | use super::*; 42 | 43 | #[test] 44 | fn test_136() { 45 | assert_eq!(Solution::single_number(vec![2, 2, 1]), 1); 46 | assert_eq!(Solution::single_number(vec![4, 1, 2, 1, 2]), 4); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/solution/s0140_word_break_ii.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [140] Word Break II 3 | * 4 | * Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. 5 | * 6 | * Note: 7 | * 8 | * 9 | * The same word in the dictionary may be reused multiple times in the segmentation. 10 | * You may assume the dictionary does not contain duplicate words. 11 | * 12 | * 13 | * Example 1: 14 | * 15 | * 16 | * Input: 17 | * s = "catsanddog" 18 | * wordDict = ["cat", "cats", "and", "sand", "dog"] 19 | * Output: 20 | * [ 21 | * "cats and dog", 22 | * "cat sand dog" 23 | * ] 24 | * 25 | * 26 | * Example 2: 27 | * 28 | * 29 | * Input: 30 | * s = "pineapplepenapple" 31 | * wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] 32 | * Output: 33 | * [ 34 | * "pine apple pen apple", 35 | * "pineapple pen apple", 36 | * "pine applepen apple" 37 | * ] 38 | * Explanation: Note that you are allowed to reuse a dictionary word. 39 | * 40 | * 41 | * Example 3: 42 | * 43 | * 44 | * Input: 45 | * s = "catsandog" 46 | * wordDict = ["cats", "dog", "sand", "and", "cat"] 47 | * Output: 48 | * [] 49 | * 50 | */ 51 | pub struct Solution {} 52 | 53 | // problem: https://leetcode.com/problems/word-break-ii/ 54 | // discuss: https://leetcode.com/problems/word-break-ii/discuss/?currentPage=1&orderBy=most_votes&query= 55 | 56 | // submission codes start here 57 | 58 | impl Solution { 59 | pub fn word_break(s: String, word_dict: Vec) -> Vec { 60 | vec![] 61 | } 62 | } 63 | 64 | // submission codes end 65 | 66 | #[cfg(test)] 67 | mod tests { 68 | use super::*; 69 | 70 | #[test] 71 | fn test_140() {} 72 | } 73 | -------------------------------------------------------------------------------- /src/solution/s0143_reorder_list.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [143] Reorder List 3 | * 4 | * Given a singly linked list L: L0→L1→…→Ln-1→Ln,
5 | * reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… 6 | * 7 | * You may not modify the values in the list's nodes, only nodes itself may be changed. 8 | * 9 | * Example 1: 10 | * 11 | * 12 | * Given 1->2->3->4, reorder it to 1->4->2->3. 13 | * 14 | * Example 2: 15 | * 16 | * 17 | * Given 1->2->3->4->5, reorder it to 1->5->2->4->3. 18 | * 19 | * 20 | */ 21 | pub struct Solution {} 22 | use crate::util::linked_list::{to_list, ListNode}; 23 | 24 | // problem: https://leetcode.com/problems/reorder-list/ 25 | // discuss: https://leetcode.com/problems/reorder-list/discuss/?currentPage=1&orderBy=most_votes&query= 26 | 27 | // submission codes start here 28 | 29 | /* 30 | 1->2->3->4->5 31 | 32 | 1->2->3<-4<-5 33 | 34 | 1->5->2->4->3 35 | */ 36 | impl Solution { 37 | pub fn reorder_list(head: &mut Option>) { 38 | // TODO 39 | } 40 | } 41 | 42 | // submission codes end 43 | 44 | #[cfg(test)] 45 | mod tests { 46 | use super::*; 47 | 48 | #[test] 49 | fn test_143() {} 50 | } 51 | -------------------------------------------------------------------------------- /src/solution/s0144_binary_tree_preorder_traversal.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [144] Binary Tree Preorder Traversal 3 | * 4 | * Given a binary tree, return the preorder traversal of its nodes' values. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: [1,null,2,3] 10 | * 1 11 | * \ 12 | * 2 13 | * / 14 | * 3 15 | * 16 | * Output: [1,2,3] 17 | * 18 | * 19 | * Follow up: Recursive solution is trivial, could you do it iteratively? 20 | * 21 | */ 22 | pub struct Solution {} 23 | use crate::util::tree::{to_tree, TreeNode}; 24 | 25 | // problem: https://leetcode.com/problems/binary-tree-preorder-traversal/ 26 | // discuss: https://leetcode.com/problems/binary-tree-preorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= 27 | 28 | // submission codes start here 29 | 30 | use std::cell::RefCell; 31 | use std::rc::Rc; 32 | impl Solution { 33 | pub fn preorder_traversal(root: Option>>) -> Vec { 34 | let mut res = Vec::new(); 35 | Solution::helper(root, &mut res); 36 | res 37 | } 38 | 39 | fn helper(root: Option>>, vec: &mut Vec) { 40 | if let Some(node) = root { 41 | vec.push(node.borrow().val); 42 | Solution::helper(node.borrow().left.clone(), vec); 43 | Solution::helper(node.borrow().right.clone(), vec); 44 | } 45 | } 46 | } 47 | 48 | // submission codes end 49 | 50 | #[cfg(test)] 51 | mod tests { 52 | use super::*; 53 | 54 | #[test] 55 | fn test_144() { 56 | assert_eq!( 57 | Solution::preorder_traversal(tree![1, null, 2, 3]), 58 | vec![1, 2, 3] 59 | ); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/solution/s0145_binary_tree_postorder_traversal.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [145] Binary Tree Postorder Traversal 3 | * 4 | * Given a binary tree, return the postorder traversal of its nodes' values. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: [1,null,2,3] 10 | * 1 11 | * \ 12 | * 2 13 | * / 14 | * 3 15 | * 16 | * Output: [3,2,1] 17 | * 18 | * 19 | * Follow up: Recursive solution is trivial, could you do it iteratively? 20 | * 21 | */ 22 | pub struct Solution {} 23 | use crate::util::tree::{to_tree, TreeNode}; 24 | 25 | // problem: https://leetcode.com/problems/binary-tree-postorder-traversal/ 26 | // discuss: https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= 27 | 28 | // submission codes start here 29 | 30 | use std::cell::RefCell; 31 | use std::rc::Rc; 32 | impl Solution { 33 | pub fn postorder_traversal(root: Option>>) -> Vec { 34 | let mut res = Vec::new(); 35 | Solution::helper(root, &mut res); 36 | res 37 | } 38 | 39 | fn helper(root: Option>>, vec: &mut Vec) { 40 | if let Some(node) = root { 41 | Solution::helper(node.borrow().left.clone(), vec); 42 | Solution::helper(node.borrow().right.clone(), vec); 43 | vec.push(node.borrow().val); 44 | } 45 | } 46 | } 47 | 48 | // submission codes end 49 | 50 | #[cfg(test)] 51 | mod tests { 52 | use super::*; 53 | 54 | #[test] 55 | fn test_145() { 56 | assert_eq!( 57 | Solution::postorder_traversal(tree![1, null, 2, 3]), 58 | vec![3, 2, 1] 59 | ); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/solution/s0147_insertion_sort_list.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [147] Insertion Sort List 3 | * 4 | * Sort a linked list using insertion sort. 5 | * 6 | *
    7 | *
8 | * 9 | *
10 | * A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
11 | * With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list

12 | * 13 | * 14 | *
    15 | *
16 | * 17 | * Algorithm of Insertion Sort: 18 | * 19 | *
    20 | * Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. 21 | * At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. 22 | * It repeats until no input elements remain. 23 | *
24 | * 25 | *
26 | * Example 1: 27 | * 28 | * 29 | * Input: 4->2->1->3 30 | * Output: 1->2->3->4 31 | * 32 | * 33 | * Example 2: 34 | * 35 | * 36 | * Input: -1->5->3->4->0 37 | * Output: -1->0->3->4->5 38 | * 39 | * 40 | */ 41 | pub struct Solution {} 42 | use crate::util::linked_list::{to_list, ListNode}; 43 | 44 | // problem: https://leetcode.com/problems/insertion-sort-list/ 45 | // discuss: https://leetcode.com/problems/insertion-sort-list/discuss/?currentPage=1&orderBy=most_votes&query= 46 | 47 | // submission codes start here 48 | 49 | // TODO; boring 50 | impl Solution { 51 | pub fn insertion_sort_list(head: Option>) -> Option> { 52 | None 53 | } 54 | } 55 | 56 | // submission codes end 57 | 58 | #[cfg(test)] 59 | mod tests { 60 | use super::*; 61 | 62 | #[test] 63 | fn test_147() {} 64 | } 65 | -------------------------------------------------------------------------------- /src/solution/s0152_maximum_product_subarray.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [152] Maximum Product Subarray 3 | * 4 | * Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: [2,3,-2,4] 10 | * Output: 6 11 | * Explanation: [2,3] has the largest product 6. 12 | * 13 | * 14 | * Example 2: 15 | * 16 | * 17 | * Input: [-2,0,-1] 18 | * Output: 0 19 | * Explanation: The result cannot be 2, because [-2,-1] is not a subarray. 20 | * 21 | */ 22 | pub struct Solution {} 23 | 24 | // problem: https://leetcode.com/problems/maximum-product-subarray/ 25 | // discuss: https://leetcode.com/problems/maximum-product-subarray/discuss/?currentPage=1&orderBy=most_votes&query= 26 | 27 | // submission codes start here 28 | 29 | /* 30 | f[i], g[i] means the max positive value and max negative value for the sub-seq end with index i 31 | 32 | then we have: 33 | 34 | f[i], g[i] = if nums[i] == 0 { 35 | 0, 0 36 | } else if nums[i] > 0 { 37 | f[i-1] * nums[i], g[i-1] * nums[i] 38 | } else if nums[i] < 0 { 39 | g[i-1] * nums[i], f[i-1] * nums[i] 40 | } 41 | */ 42 | 43 | impl Solution { 44 | pub fn max_product(nums: Vec) -> i32 { 45 | let mut max = nums[0]; 46 | let mut neg_max = 0; 47 | let mut pos_max = 0; 48 | for num in nums.into_iter() { 49 | if num == 0 { 50 | neg_max = 0; 51 | pos_max = 0; 52 | max = i32::max(max, 0); 53 | } else if num > 0 { 54 | pos_max = i32::max(pos_max * num, num); 55 | neg_max = neg_max * num; 56 | } else { 57 | let pos_pre = pos_max; 58 | pos_max = neg_max * num; 59 | neg_max = i32::min(pos_pre * num, num); 60 | } 61 | if pos_max != 0 { 62 | max = i32::max(max, pos_max); 63 | } 64 | } 65 | max 66 | } 67 | } 68 | 69 | // submission codes end 70 | 71 | #[cfg(test)] 72 | mod tests { 73 | use super::*; 74 | 75 | #[test] 76 | fn test_152() { 77 | assert_eq!(Solution::max_product(vec![2, 3, -2, 4]), 6); 78 | assert_eq!(Solution::max_product(vec![-2, 0, -1]), 0); 79 | assert_eq!(Solution::max_product(vec![-4, -3, -2]), 12); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/solution/s0153_find_minimum_in_rotated_sorted_array.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [153] Find Minimum in Rotated Sorted Array 3 | * 4 | * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 5 | * 6 | * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 7 | * 8 | * Find the minimum element. 9 | * 10 | * You may assume no duplicate exists in the array. 11 | * 12 | * Example 1: 13 | * 14 | * 15 | * Input: [3,4,5,1,2] 16 | * Output: 1 17 | * 18 | * 19 | * Example 2: 20 | * 21 | * 22 | * Input: [4,5,6,7,0,1,2] 23 | * Output: 0 24 | * 25 | * 26 | */ 27 | pub struct Solution {} 28 | 29 | // problem: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 30 | // discuss: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= 31 | 32 | // submission codes start here 33 | 34 | impl Solution { 35 | pub fn find_min(nums: Vec) -> i32 { 36 | let mut size = nums.len(); 37 | if size == 0 { 38 | return -1; 39 | } 40 | let mut base = 0_usize; 41 | while size > 1 { 42 | let half = size / 2; 43 | let mid = base + half; 44 | if nums[mid] > nums[base] { 45 | base = mid; 46 | } 47 | size -= half; 48 | } 49 | i32::min(nums[base], nums[(base + 1) % nums.len()]) 50 | } 51 | } 52 | 53 | // submission codes end 54 | 55 | #[cfg(test)] 56 | mod tests { 57 | use super::*; 58 | 59 | #[test] 60 | fn test_153() { 61 | assert_eq!(Solution::find_min(vec![4, 5, 6, 1, 2, 3]), 1); 62 | assert_eq!(Solution::find_min(vec![4, 5, 6, 7, 0, 1, 2]), 0); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/solution/s0154_find_minimum_in_rotated_sorted_array_ii.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [154] Find Minimum in Rotated Sorted Array II 3 | * 4 | * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 5 | * 6 | * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 7 | * 8 | * Find the minimum element. 9 | * 10 | * The array may contain duplicates. 11 | * 12 | * Example 1: 13 | * 14 | * 15 | * Input: [1,3,5] 16 | * Output: 1 17 | * 18 | * Example 2: 19 | * 20 | * 21 | * Input: [2,2,2,0,1] 22 | * Output: 0 23 | * 24 | * Note: 25 | * 26 | * 27 | * This is a follow up problem to Find Minimum in Rotated Sorted Array. 28 | * Would allow duplicates affect the run-time complexity? How and why? 29 | * 30 | * 31 | */ 32 | pub struct Solution {} 33 | 34 | // problem: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ 35 | // discuss: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/discuss/?currentPage=1&orderBy=most_votes&query= 36 | 37 | // submission codes start here 38 | 39 | /* 40 | 针对无重复的做法, 只要二分搜索找折点即可: 假如 nums[mid] > nums[base] 那么转折点一定在右侧, 否则在左侧 41 | 42 | 但假如有重复, 就可能有 nums[mid] == nums[base], 这时就尴尬了, 无法确定转折点在左半部分还是右半部分 43 | 44 | 可以考虑一个数组, [1,1,1,1,1,1,1,0,1,1,1,1,1,1] 这个数组无论怎么去找 0, 时间复杂度无法低于 O(N) 45 | 46 | 但假如不是这种极端情况, 那么二分搜索还是能优化的, 在 153 的基础上, 碰到相等就跳过即可 47 | */ 48 | impl Solution { 49 | pub fn find_min(nums: Vec) -> i32 { 50 | let mut lo = 0; 51 | let mut hi = nums.len() - 1; 52 | let mut mid = 0; 53 | while lo < hi { 54 | mid = lo + (hi - lo) / 2; 55 | if (nums[mid] > nums[hi]) { 56 | lo = mid + 1; 57 | } else if (nums[mid] < nums[hi]) { 58 | hi = mid; 59 | } else { 60 | hi -= 1; 61 | } 62 | } 63 | return nums[lo]; 64 | } 65 | } 66 | 67 | // submission codes end 68 | 69 | #[cfg(test)] 70 | mod tests { 71 | use super::*; 72 | 73 | #[test] 74 | fn test_154() { 75 | assert_eq!(Solution::find_min(vec![1, 2, 2, 2, 2, 2]), 1); 76 | assert_eq!(Solution::find_min(vec![1, 3, 3]), 1); 77 | assert_eq!(Solution::find_min(vec![3, 1, 3, 3]), 1); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/solution/s0162_find_peak_element.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [162] Find Peak Element 3 | * 4 | * A peak element is an element that is greater than its neighbors. 5 | * 6 | * Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. 7 | * 8 | * The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 9 | * 10 | * You may imagine that nums[-1] = nums[n] = -∞. 11 | * 12 | * Example 1: 13 | * 14 | * 15 | * Input: nums = [1,2,3,1] 16 | * Output: 2 17 | * Explanation: 3 is a peak element and your function should return the index number 2. 18 | * 19 | * Example 2: 20 | * 21 | * 22 | * Input: nums = [1,2,1,3,5,6,4] 23 | * Output: 1 or 5 24 | * Explanation: Your function can return either index number 1 where the peak element is 2, 25 | * or index number 5 where the peak element is 6. 26 | * 27 | * 28 | * Note: 29 | * 30 | * Your solution should be in logarithmic complexity. 31 | * 32 | */ 33 | pub struct Solution {} 34 | 35 | // problem: https://leetcode.com/problems/find-peak-element/ 36 | // discuss: https://leetcode.com/problems/find-peak-element/discuss/?currentPage=1&orderBy=most_votes&query= 37 | 38 | // submission codes start here 39 | 40 | impl Solution { 41 | pub fn find_peak_element(nums: Vec) -> i32 { 42 | let (mut lo, mut hi) = (0_usize, nums.len() - 1); 43 | let mut mid = 0; 44 | while lo < hi { 45 | mid = (hi - lo) / 2 + lo; 46 | if mid + 1 < nums.len() && nums[mid] < nums[mid + 1] { 47 | lo = mid + 1; 48 | } else { 49 | hi = mid; 50 | } 51 | } 52 | lo as i32 53 | } 54 | } 55 | 56 | // submission codes end 57 | 58 | #[cfg(test)] 59 | mod tests { 60 | use super::*; 61 | 62 | #[test] 63 | fn test_162() { 64 | assert_eq!(Solution::find_peak_element(vec![1, 2, 3, 1]), 2); 65 | assert_eq!(Solution::find_peak_element(vec![1, 2, 1, 3, 5, 6, 4]), 5); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/solution/s0164_maximum_gap.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [164] Maximum Gap 3 | * 4 | * Given an unsorted array, find the maximum difference between the successive elements in its sorted form. 5 | * 6 | * Return 0 if the array contains less than 2 elements. 7 | * 8 | * Example 1: 9 | * 10 | * 11 | * Input: [3,6,9,1] 12 | * Output: 3 13 | * Explanation: The sorted form of the array is [1,3,6,9], either 14 | * (3,6) or (6,9) has the maximum difference 3. 15 | * 16 | * Example 2: 17 | * 18 | * 19 | * Input: [10] 20 | * Output: 0 21 | * Explanation: The array contains less than 2 elements, therefore return 0. 22 | * 23 | * Note: 24 | * 25 | * 26 | * You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range. 27 | * Try to solve it in linear time/space. 28 | * 29 | * 30 | */ 31 | pub struct Solution {} 32 | 33 | // problem: https://leetcode.com/problems/maximum-gap/ 34 | // discuss: https://leetcode.com/problems/maximum-gap/discuss/?currentPage=1&orderBy=most_votes&query= 35 | 36 | // submission codes start here 37 | /* 38 | 想不出来, 一看解析居然是 Radix Sort 或 Bucket Sort, 我就 ??? 了... 39 | 40 | 最佳算法是 Bucket Sort 吗? (桶大小取 max - min / len 那种), 看时间复杂度好像是这样 41 | 42 | 但假如整体排布非常稠密, 那么这个聪明的算法也就退化成了桶大小为 1 的桶排序 43 | */ 44 | impl Solution { 45 | pub fn maximum_gap(nums: Vec) -> i32 { 46 | let mut nums = nums; 47 | nums.sort_unstable(); 48 | let mut gap = 0; 49 | for i in 1..nums.len() { 50 | gap = i32::max(nums[i] - nums[i - 1], gap); 51 | } 52 | gap 53 | } 54 | } 55 | 56 | // submission codes end 57 | 58 | #[cfg(test)] 59 | mod tests { 60 | use super::*; 61 | 62 | #[test] 63 | fn test_164() { 64 | assert_eq!(Solution::maximum_gap(vec![3, 6, 9, 1]), 3); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/solution/s0166_fraction_to_recurring_decimal.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [166] Fraction to Recurring Decimal 3 | * 4 | * Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. 5 | * 6 | * If the fractional part is repeating, enclose the repeating part in parentheses. 7 | * 8 | * Example 1: 9 | * 10 | * 11 | * Input: numerator = 1, denominator = 2 12 | * Output: "0.5" 13 | * 14 | * 15 | * Example 2: 16 | * 17 | * 18 | * Input: numerator = 2, denominator = 1 19 | * Output: "2" 20 | * 21 | * Example 3: 22 | * 23 | * 24 | * Input: numerator = 2, denominator = 3 25 | * Output: "0.(6)" 26 | * 27 | * 28 | */ 29 | pub struct Solution {} 30 | 31 | // problem: https://leetcode.com/problems/fraction-to-recurring-decimal/ 32 | // discuss: https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/?currentPage=1&orderBy=most_votes&query= 33 | 34 | // submission codes start here 35 | 36 | // TODO 37 | impl Solution { 38 | pub fn fraction_to_decimal(numerator: i32, denominator: i32) -> String { 39 | "".to_owned() 40 | } 41 | } 42 | 43 | // submission codes end 44 | 45 | #[cfg(test)] 46 | mod tests { 47 | use super::*; 48 | 49 | #[test] 50 | fn test_166() {} 51 | } 52 | -------------------------------------------------------------------------------- /src/solution/s0167_two_sum_ii_input_array_is_sorted.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [167] Two Sum II - Input array is sorted 3 | * 4 | * Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. 5 | * 6 | * The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. 7 | * 8 | * Note: 9 | * 10 | * 11 | * Your returned answers (both index1 and index2) are not zero-based. 12 | * You may assume that each input would have exactly one solution and you may not use the same element twice. 13 | * 14 | * 15 | * Example: 16 | * 17 | * 18 | * Input: numbers = [2,7,11,15], target = 9 19 | * Output: [1,2] 20 | * Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. 21 | * 22 | */ 23 | pub struct Solution {} 24 | 25 | // problem: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ 26 | // discuss: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/?currentPage=1&orderBy=most_votes&query= 27 | 28 | // submission codes start here 29 | 30 | impl Solution { 31 | pub fn two_sum(numbers: Vec, target: i32) -> Vec { 32 | let mut i = 0_usize; 33 | let mut j = numbers.len() - 1; 34 | while i < j { 35 | let sum = numbers[i] + numbers[j]; 36 | if sum > target { 37 | j -= 1; 38 | } else if sum < target { 39 | i += 1; 40 | } else { 41 | break; 42 | } 43 | } 44 | return vec![i as i32 + 1, j as i32 + 1]; 45 | } 46 | } 47 | 48 | // submission codes end 49 | 50 | #[cfg(test)] 51 | mod tests { 52 | use super::*; 53 | 54 | #[test] 55 | fn test_167() { 56 | assert_eq!(Solution::two_sum(vec![2, 7, 11, 15], 9), vec![1, 2]); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/solution/s0168_excel_sheet_column_title.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [168] Excel Sheet Column Title 3 | * 4 | * Given a positive integer, return its corresponding column title as appear in an Excel sheet. 5 | * 6 | * For example: 7 | * 8 | * 9 | * 1 -> A 10 | * 2 -> B 11 | * 3 -> C 12 | * ... 13 | * 26 -> Z 14 | * 27 -> AA 15 | * 28 -> AB 16 | * ... 17 | * 18 | * 19 | * Example 1: 20 | * 21 | * 22 | * Input: 1 23 | * Output: "A" 24 | * 25 | * 26 | * Example 2: 27 | * 28 | * 29 | * Input: 28 30 | * Output: "AB" 31 | * 32 | * 33 | * Example 3: 34 | * 35 | * 36 | * Input: 701 37 | * Output: "ZY" 38 | * 39 | */ 40 | pub struct Solution {} 41 | 42 | // problem: https://leetcode.com/problems/excel-sheet-column-title/ 43 | // discuss: https://leetcode.com/problems/excel-sheet-column-title/discuss/?currentPage=1&orderBy=most_votes&query= 44 | 45 | // submission codes start here 46 | 47 | impl Solution { 48 | pub fn convert_to_title(n: i32) -> String { 49 | let base = 26; 50 | let mut n = n; 51 | let mut res = Vec::new(); 52 | while n > 0 { 53 | let mut code = (n % base) as u8; 54 | n = n / base; 55 | if code == 0 { 56 | n -= 1; 57 | code = base as u8; 58 | }; 59 | let alphabetic = (('A' as u8) + (code - 1_u8)) as char; 60 | res.push(alphabetic); 61 | } 62 | res.reverse(); 63 | res.into_iter().collect() 64 | } 65 | } 66 | 67 | // submission codes end 68 | 69 | #[cfg(test)] 70 | mod tests { 71 | use super::*; 72 | 73 | #[test] 74 | fn test_168() { 75 | assert_eq!(Solution::convert_to_title(28), "AB".to_owned()); 76 | assert_eq!(Solution::convert_to_title(1), "A".to_owned()); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/solution/s0169_majority_element.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [169] Majority Element 3 | * 4 | * Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 5 | * 6 | * You may assume that the array is non-empty and the majority element always exist in the array. 7 | * 8 | * Example 1: 9 | * 10 | * 11 | * Input: [3,2,3] 12 | * Output: 3 13 | * 14 | * Example 2: 15 | * 16 | * 17 | * Input: [2,2,1,1,1,2,2] 18 | * Output: 2 19 | * 20 | * 21 | */ 22 | pub struct Solution {} 23 | 24 | // problem: https://leetcode.com/problems/majority-element/ 25 | // discuss: https://leetcode.com/problems/majority-element/discuss/?currentPage=1&orderBy=most_votes&query= 26 | 27 | // submission codes start here 28 | 29 | /* 30 | 抄的题解:Boyer-Moore Voting Algorithm 31 | 自己只能想到 HashMap 和排序, 真是太鸡儿菜了... 32 | 33 | Boyer-Moore Voting Algorithm 的思路是假设当前值为主元素, 碰到当前值则 +1, 非当前值则 -1, 计数器一旦归零, 34 | 就取下一个数为主元素 35 | 36 | 最后留下的数一定主元素 37 | 38 | 证明也很简单, 假设我们从第 i 位开始选择了一个数 A, 并且这个数 A 保持到了循环终止, 那么: 39 | 40 | 我们知道, 第 nums[i..n] 中, A 是主元素, nums[0..i] 中, 有一个数 B 出现了一半的次数 41 | 42 | 假如 A = B, 那么 A 出现了大于一半的次数, A 一定是主元素 43 | 44 | 假如 A != B, 且主元素不是 A, 那么 B 包括其他任何数在整个数组中出现的次数一定不到一半(因为 B 包括其他任何数 45 | 在前半部分**至多**出现一半, 而在后半部分不到一半), 因此不存在主元素, 这与题目给定的"一定存在主元素"矛盾, 因此 46 | A 一定是主元素 47 | */ 48 | 49 | impl Solution { 50 | pub fn majority_element(nums: Vec) -> i32 { 51 | let mut count = 0; 52 | let mut candidate = 0; 53 | for &num in nums.iter() { 54 | if count == 0 { 55 | candidate = num; 56 | } 57 | count += if num == candidate { 1 } else { -1 }; 58 | } 59 | candidate 60 | } 61 | } 62 | 63 | // submission codes end 64 | 65 | #[cfg(test)] 66 | mod tests { 67 | use super::*; 68 | 69 | #[test] 70 | fn test_169() { 71 | assert_eq!(Solution::majority_element(vec![2, 2, 1, 1, 1, 2, 2]), 2); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/solution/s0171_excel_sheet_column_number.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [171] Excel Sheet Column Number 3 | * 4 | * Given a column title as appear in an Excel sheet, return its corresponding column number. 5 | * 6 | * For example: 7 | * 8 | * 9 | * A -> 1 10 | * B -> 2 11 | * C -> 3 12 | * ... 13 | * Z -> 26 14 | * AA -> 27 15 | * AB -> 28 16 | * ... 17 | * 18 | * 19 | * Example 1: 20 | * 21 | * 22 | * Input: "A" 23 | * Output: 1 24 | * 25 | * 26 | * Example 2: 27 | * 28 | * 29 | * Input: "AB" 30 | * Output: 28 31 | * 32 | * 33 | * Example 3: 34 | * 35 | * 36 | * Input: "ZY" 37 | * Output: 701 38 | * 39 | */ 40 | pub struct Solution {} 41 | 42 | // problem: https://leetcode.com/problems/excel-sheet-column-number/ 43 | // discuss: https://leetcode.com/problems/excel-sheet-column-number/discuss/?currentPage=1&orderBy=most_votes&query= 44 | 45 | // submission codes start here 46 | 47 | // TODO: boring 48 | impl Solution { 49 | pub fn title_to_number(s: String) -> i32 { 50 | 0 51 | } 52 | } 53 | 54 | // submission codes end 55 | 56 | #[cfg(test)] 57 | mod tests { 58 | use super::*; 59 | 60 | #[test] 61 | fn test_171() {} 62 | } 63 | -------------------------------------------------------------------------------- /src/solution/s0172_factorial_trailing_zeroes.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [172] Factorial Trailing Zeroes 3 | * 4 | * Given an integer n, return the number of trailing zeroes in n!. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: 3 10 | * Output: 0 11 | * Explanation: 3! = 6, no trailing zero. 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: 5 17 | * Output: 1 18 | * Explanation: 5! = 120, one trailing zero. 19 | * 20 | * Note: Your solution should be in logarithmic time complexity. 21 | * 22 | */ 23 | pub struct Solution {} 24 | 25 | // problem: https://leetcode.com/problems/factorial-trailing-zeroes/ 26 | // discuss: https://leetcode.com/problems/factorial-trailing-zeroes/discuss/?currentPage=1&orderBy=most_votes&query= 27 | 28 | // submission codes start here 29 | 30 | impl Solution { 31 | pub fn trailing_zeroes(n: i32) -> i32 { 32 | let mut five_count = 0; 33 | let mut n = n; 34 | while n > 0 { 35 | n = n / 5; 36 | five_count += n; 37 | } 38 | five_count 39 | } 40 | } 41 | 42 | // submission codes end 43 | 44 | #[cfg(test)] 45 | mod tests { 46 | use super::*; 47 | 48 | #[test] 49 | fn test_172() { 50 | assert_eq!(Solution::trailing_zeroes(3), 0); 51 | assert_eq!(Solution::trailing_zeroes(5), 1); 52 | assert_eq!(Solution::trailing_zeroes(20), 4); 53 | assert_eq!(Solution::trailing_zeroes(1808548329), 452137076); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/solution/s0179_largest_number.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [179] Largest Number 3 | * 4 | * Given a list of non negative integers, arrange them such that they form the largest number. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: [10,2] 10 | * Output: "210" 11 | * 12 | * Example 2: 13 | * 14 | * 15 | * Input: [3,30,34,5,9] 16 | * Output: "9534330" 17 | * 18 | * 19 | * Note: The result may be very large, so you need to return a string instead of an integer. 20 | * 21 | */ 22 | pub struct Solution {} 23 | 24 | // problem: https://leetcode.com/problems/largest-number/ 25 | // discuss: https://leetcode.com/problems/largest-number/discuss/?currentPage=1&orderBy=most_votes&query= 26 | 27 | // submission codes start here 28 | 29 | impl Solution { 30 | pub fn largest_number(nums: Vec) -> String { 31 | let mut nums = nums 32 | .into_iter() 33 | .map(|num| num.to_string()) 34 | .collect::>(); 35 | nums.sort_unstable_by(|a, b| format!("{}{}", b, a).cmp(&format!("{}{}", a, b))); 36 | if nums[0] == "0" { 37 | return "0".to_owned(); 38 | } 39 | nums.iter().fold(String::new(), |mut s, num| { 40 | s.push_str(num); 41 | s 42 | }) 43 | } 44 | } 45 | 46 | // submission codes end 47 | 48 | #[cfg(test)] 49 | mod tests { 50 | use super::*; 51 | 52 | #[test] 53 | fn test_179() { 54 | assert_eq!( 55 | Solution::largest_number(vec![3, 30, 34, 5, 9]), 56 | "9534330".to_owned() 57 | ); 58 | assert_eq!(Solution::largest_number(vec![121, 12]), "12121".to_owned()); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/solution/s0189_rotate_array.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [189] Rotate Array 3 | * 4 | * Given an array, rotate the array to the right by k steps, where k is non-negative. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: [1,2,3,4,5,6,7] and k = 3 10 | * Output: [5,6,7,1,2,3,4] 11 | * Explanation: 12 | * rotate 1 steps to the right: [7,1,2,3,4,5,6] 13 | * rotate 2 steps to the right: [6,7,1,2,3,4,5] 14 | * rotate 3 steps to the right: [5,6,7,1,2,3,4] 15 | * 16 | * 17 | * Example 2: 18 | * 19 | * 20 | * Input: [-1,-100,3,99] and k = 2 21 | * Output: [3,99,-1,-100] 22 | * Explanation: 23 | * rotate 1 steps to the right: [99,-1,-100,3] 24 | * rotate 2 steps to the right: [3,99,-1,-100] 25 | * 26 | * 27 | * Note: 28 | * 29 | * 30 | * Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. 31 | * Could you do it in-place with O(1) extra space? 32 | * 33 | */ 34 | pub struct Solution {} 35 | 36 | // problem: https://leetcode.com/problems/rotate-array/ 37 | // discuss: https://leetcode.com/problems/rotate-array/discuss/?currentPage=1&orderBy=most_votes&query= 38 | 39 | // submission codes start here 40 | 41 | impl Solution { 42 | pub fn rotate(nums: &mut Vec, k: i32) { 43 | let offset = (k as usize) % nums.len(); 44 | if offset == 0 { 45 | return; 46 | } 47 | let mut idx = 0; 48 | let mut num = nums[0]; 49 | let mut start_idx = 0; 50 | for _ in 0..nums.len() { 51 | idx = (idx + offset) % nums.len(); 52 | let temp = num; 53 | num = nums[idx]; 54 | nums[idx] = temp; 55 | if idx == start_idx { 56 | idx += 1; 57 | start_idx = idx; 58 | num = nums[idx]; 59 | } 60 | } 61 | } 62 | } 63 | 64 | // submission codes end 65 | 66 | #[cfg(test)] 67 | mod tests { 68 | use super::*; 69 | 70 | #[test] 71 | fn test_189() { 72 | let mut nums = vec![1, 2, 3, 4, 5, 6, 7]; 73 | Solution::rotate(&mut nums, 3); 74 | assert_eq!(nums, vec![5, 6, 7, 1, 2, 3, 4]); 75 | let mut nums = vec![1, 2, 3, 4, 5, 6]; 76 | Solution::rotate(&mut nums, 2); 77 | assert_eq!(nums, vec![5, 6, 1, 2, 3, 4]); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/solution/s0198_house_robber.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [198] House Robber 3 | * 4 | * You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. 5 | * 6 | * Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. 7 | * 8 | * Example 1: 9 | * 10 | * 11 | * Input: [1,2,3,1] 12 | * Output: 4 13 | * Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). 14 | * Total amount you can rob = 1 + 3 = 4. 15 | * 16 | * Example 2: 17 | * 18 | * 19 | * Input: [2,7,9,3,1] 20 | * Output: 12 21 | * Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). 22 | * Total amount you can rob = 2 + 9 + 1 = 12. 23 | * 24 | * 25 | */ 26 | pub struct Solution {} 27 | 28 | // problem: https://leetcode.com/problems/house-robber/ 29 | // discuss: https://leetcode.com/problems/house-robber/discuss/?currentPage=1&orderBy=most_votes&query= 30 | 31 | // submission codes start here 32 | 33 | /* 34 | 动态规划, 记抢到第 i 户为止的最大收益为 F[i], 则: 35 | 36 | i 有两种情况, 抢或不抢, 抢的话则最大收益是 F[i-2] + nums[i], 37 | 不抢则保持和前一次结束的收益一致, 等于 F[i-1], 于是: 38 | 39 | F[i] = i32::max(nums[i] + F[i-2], F[i-1]) 40 | 41 | 观察到 F[i] 只依赖 F[i-1] 和 F[i-2], 可以用常数空间复杂度完成 42 | */ 43 | impl Solution { 44 | pub fn rob(nums: Vec) -> i32 { 45 | let mut former_max = 0; 46 | let mut curr_max = 0; 47 | for &num in nums.iter() { 48 | let mut temp = curr_max; 49 | curr_max = i32::max(former_max + num, curr_max); 50 | former_max = temp; 51 | } 52 | curr_max 53 | } 54 | } 55 | 56 | // submission codes end 57 | 58 | #[cfg(test)] 59 | mod tests { 60 | use super::*; 61 | 62 | #[test] 63 | fn test_198() { 64 | assert_eq!(Solution::rob(vec![2, 7, 9, 3, 1]), 12); 65 | assert_eq!(Solution::rob(vec![2, 7, 9, 10, 1]), 17); 66 | assert_eq!(Solution::rob(vec![2, 1, 1, 2]), 4); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/solution/s0199_binary_tree_right_side_view.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [199] Binary Tree Right Side View 3 | * 4 | * Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: [1,2,3,null,5,null,4] 10 | * Output: [1, 3, 4] 11 | * Explanation: 12 | * 13 | * 1 <--- 14 | * / \ 15 | * 2 3 <--- 16 | * \ \ 17 | * 5 4 <--- 18 | * 19 | */ 20 | pub struct Solution {} 21 | use crate::util::tree::{to_tree, TreeNode}; 22 | 23 | // problem: https://leetcode.com/problems/binary-tree-right-side-view/ 24 | // discuss: https://leetcode.com/problems/binary-tree-right-side-view/discuss/?currentPage=1&orderBy=most_votes&query= 25 | 26 | // submission codes start here 27 | 28 | use std::cell::RefCell; 29 | use std::collections::VecDeque; 30 | use std::rc::Rc; 31 | impl Solution { 32 | pub fn right_side_view(root: Option>>) -> Vec { 33 | let mut res = Vec::new(); 34 | let mut current_level = 0; 35 | if root.is_none() { 36 | return res; 37 | } 38 | let mut deq = VecDeque::new(); 39 | deq.push_back((0, root.clone())); 40 | res.push(root.as_ref().unwrap().borrow().val); 41 | while !deq.is_empty() { 42 | if let Some((level, Some(node))) = deq.pop_front() { 43 | deq.push_back((level + 1, node.borrow().right.clone())); 44 | deq.push_back((level + 1, node.borrow().left.clone())); 45 | if level > current_level { 46 | res.push(node.borrow().val); 47 | current_level = level; 48 | } 49 | } 50 | } 51 | res 52 | } 53 | } 54 | 55 | // submission codes end 56 | 57 | #[cfg(test)] 58 | mod tests { 59 | use super::*; 60 | 61 | #[test] 62 | fn test_199() { 63 | assert_eq!( 64 | Solution::right_side_view(tree![1, 2, 3, null, 5, null, 4]), 65 | vec![1, 3, 4] 66 | ); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/solution/s0201_bitwise_and_of_numbers_range.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [201] Bitwise AND of Numbers Range 3 | * 4 | * Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: [5,7] 10 | * Output: 4 11 | * 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: [0,1] 17 | * Output: 0 18 | */ 19 | pub struct Solution {} 20 | 21 | // problem: https://leetcode.com/problems/bitwise-and-of-numbers-range/ 22 | // discuss: https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/?currentPage=1&orderBy=most_votes&query= 23 | 24 | // submission codes start here 25 | 26 | // just find the highest bit 1 of m and n 27 | impl Solution { 28 | pub fn range_bitwise_and(m: i32, n: i32) -> i32 { 29 | let mut m = m; 30 | let mut n = n; 31 | if m == 0 { 32 | return 0; 33 | } 34 | let mut step = 1; 35 | while m != n { 36 | // shortcut 37 | if m == 0 { 38 | return 0; 39 | } 40 | m >>= 1; 41 | n >>= 1; 42 | step <<= 1; 43 | } 44 | return m * step; 45 | } 46 | } 47 | 48 | // submission codes end 49 | 50 | #[cfg(test)] 51 | mod tests { 52 | use super::*; 53 | 54 | #[test] 55 | fn test_201() { 56 | assert_eq!(Solution::range_bitwise_and(5, 7), 4); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/solution/s0202_happy_number.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [202] Happy Number 3 | * 4 | * Write an algorithm to determine if a number is "happy". 5 | * 6 | * A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 7 | * 8 | * Example: 9 | * 10 | * 11 | * Input: 19 12 | * Output: true 13 | * Explanation: 14 | * 1^2 + 9^2 = 82 15 | * 8^2 + 2^2 = 68 16 | * 6^2 + 8^2 = 100 17 | * 1^2 + 0^2 + 0^2 = 1 18 | * 19 | */ 20 | pub struct Solution {} 21 | 22 | // problem: https://leetcode.com/problems/happy-number/ 23 | // discuss: https://leetcode.com/problems/happy-number/discuss/?currentPage=1&orderBy=most_votes&query= 24 | 25 | // submission codes start here 26 | 27 | use std::collections::HashSet; 28 | impl Solution { 29 | pub fn is_happy(n: i32) -> bool { 30 | let mut set = HashSet::new(); 31 | let mut n = n; 32 | loop { 33 | set.insert(n); 34 | let temp = Solution::next(n); 35 | if temp == 1 { 36 | return true; 37 | } 38 | if !set.insert(temp) { 39 | return false; 40 | } 41 | n = temp 42 | } 43 | return false; 44 | } 45 | 46 | fn next(n: i32) -> i32 { 47 | let mut res = 0; 48 | let mut n = n; 49 | while n != 0 { 50 | res += (n % 10).pow(2); 51 | n = n / 10; 52 | } 53 | res 54 | } 55 | } 56 | 57 | // submission codes end 58 | 59 | #[cfg(test)] 60 | mod tests { 61 | use super::*; 62 | 63 | #[test] 64 | fn test_202() { 65 | assert_eq!(Solution::is_happy(19), true); 66 | assert_eq!(Solution::is_happy(235123), false); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/solution/s0203_remove_linked_list_elements.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [203] Remove Linked List Elements 3 | * 4 | * Remove all elements from a linked list of integers that have value val. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: 1->2->6->3->4->5->6, val = 6 10 | * Output: 1->2->3->4->5 11 | * 12 | * 13 | */ 14 | pub struct Solution {} 15 | use crate::util::linked_list::{to_list, ListNode}; 16 | 17 | // problem: https://leetcode.com/problems/remove-linked-list-elements/ 18 | // discuss: https://leetcode.com/problems/remove-linked-list-elements/discuss/?currentPage=1&orderBy=most_votes&query= 19 | 20 | // submission codes start here 21 | 22 | impl Solution { 23 | pub fn remove_elements(mut head: Option>, val: i32) -> Option> { 24 | let mut dummy = Some(Box::new(ListNode::new(0))); 25 | let mut next = dummy.as_mut(); 26 | while let Some(mut inner) = head { 27 | head = inner.next.take(); 28 | if inner.val != val { 29 | next.as_mut().unwrap().next = Some(inner); 30 | next = next.unwrap().next.as_mut(); 31 | } 32 | } 33 | dummy.unwrap().next 34 | } 35 | } 36 | 37 | // submission codes end 38 | 39 | #[cfg(test)] 40 | mod tests { 41 | use super::*; 42 | 43 | #[test] 44 | fn test_203() { 45 | assert_eq!( 46 | Solution::remove_elements(linked![1, 2, 6, 3, 4, 5, 6], 6), 47 | linked![1, 2, 3, 4, 5] 48 | ); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/solution/s0204_count_primes.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [204] Count Primes 3 | * 4 | * Count the number of prime numbers less than a non-negative number, n. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: 10 10 | * Output: 4 11 | * Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 12 | * 13 | * 14 | */ 15 | pub struct Solution {} 16 | 17 | // problem: https://leetcode.com/problems/count-primes/ 18 | // discuss: https://leetcode.com/problems/count-primes/discuss/?currentPage=1&orderBy=most_votes&query= 19 | 20 | // submission codes start here 21 | 22 | impl Solution { 23 | pub fn count_primes(n: i32) -> i32 { 24 | if n <= 2 { 25 | return 0; 26 | } 27 | let mut is_prime = vec![true; n as usize]; 28 | is_prime[0] = false; 29 | is_prime[1] = false; 30 | let mut i = 2; 31 | while i * i < n { 32 | if !is_prime[i as usize] { 33 | i += 1; 34 | continue; 35 | } 36 | let mut j = i * i; 37 | while j < n { 38 | is_prime[j as usize] = false; 39 | j += i; 40 | } 41 | i += 1; 42 | } 43 | let mut count = 0; 44 | for &v in is_prime.iter() { 45 | if v { 46 | count += 1 47 | } 48 | } 49 | count 50 | } 51 | } 52 | 53 | // submission codes end 54 | 55 | #[cfg(test)] 56 | mod tests { 57 | use super::*; 58 | 59 | #[test] 60 | fn test_204() { 61 | assert_eq!(Solution::count_primes(10), 4); 62 | assert_eq!(Solution::count_primes(2), 0); 63 | assert_eq!(Solution::count_primes(3), 1); 64 | assert_eq!(Solution::count_primes(5), 2); 65 | assert_eq!(Solution::count_primes(1), 0); 66 | assert_eq!(Solution::count_primes(120), 30); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/solution/s0206_reverse_linked_list.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [206] Reverse Linked List 3 | * 4 | * Reverse a singly linked list. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: 1->2->3->4->5->NULL 10 | * Output: 5->4->3->2->1->NULL 11 | * 12 | * 13 | * Follow up: 14 | * 15 | * A linked list can be reversed either iteratively or recursively. Could you implement both? 16 | * 17 | */ 18 | pub struct Solution {} 19 | use crate::util::linked_list::{to_list, ListNode}; 20 | 21 | // problem: https://leetcode.com/problems/reverse-linked-list/ 22 | // discuss: https://leetcode.com/problems/reverse-linked-list/discuss/?currentPage=1&orderBy=most_votes&query= 23 | 24 | // submission codes start here 25 | 26 | impl Solution { 27 | pub fn reverse_list(head: Option>) -> Option> { 28 | let mut curr = head; 29 | let mut next = None; 30 | while let Some(mut inner) = curr { 31 | curr = inner.next.take(); 32 | inner.next = next; 33 | next = Some(inner); 34 | } 35 | next 36 | } 37 | } 38 | 39 | // submission codes end 40 | 41 | #[cfg(test)] 42 | mod tests { 43 | use super::*; 44 | 45 | #[test] 46 | fn test_206() { 47 | assert_eq!( 48 | Solution::reverse_list(linked![1, 2, 3, 4, 5]), 49 | linked![5, 4, 3, 2, 1] 50 | ); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/solution/s0209_minimum_size_subarray_sum.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [209] Minimum Size Subarray Sum 3 | * 4 | * Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: s = 7, nums = [2,3,1,2,4,3] 10 | * Output: 2 11 | * Explanation: the subarray [4,3] has the minimal length under the problem constraint. 12 | * 13 | *
Follow up:
14 | * 15 | *
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
16 | * 17 | */ 18 | pub struct Solution {} 19 | 20 | // problem: https://leetcode.com/problems/minimum-size-subarray-sum/ 21 | // discuss: https://leetcode.com/problems/minimum-size-subarray-sum/discuss/?currentPage=1&orderBy=most_votes&query= 22 | 23 | // submission codes start here 24 | 25 | impl Solution { 26 | pub fn min_sub_array_len(s: i32, nums: Vec) -> i32 { 27 | let (mut i, mut j) = (0_usize, 0_usize); 28 | let mut min = i32::max_value(); 29 | let mut found = false; 30 | let mut sum = 0; 31 | while j < nums.len() { 32 | sum += nums[j]; 33 | if sum >= s { 34 | found = true; 35 | while i <= j { 36 | sum -= nums[i]; 37 | i += 1; 38 | if sum < s { 39 | min = i32::min(min, j as i32 - i as i32 + 2); 40 | break; 41 | } 42 | } 43 | } 44 | j += 1; 45 | } 46 | if found { 47 | min 48 | } else { 49 | 0 50 | } 51 | } 52 | } 53 | 54 | // submission codes end 55 | 56 | #[cfg(test)] 57 | mod tests { 58 | use super::*; 59 | 60 | #[test] 61 | fn test_209() { 62 | assert_eq!(Solution::min_sub_array_len(7, vec![2, 3, 1, 2, 4, 3]), 2); 63 | assert_eq!(Solution::min_sub_array_len(4, vec![1, 4, 4]), 1); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/solution/s0212_word_search_ii.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [212] Word Search II 3 | * 4 | * Given a 2D board and a list of words from the dictionary, find all words in the board. 5 | * 6 | * Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. 7 | * 8 | * 9 | * 10 | * Example: 11 | * 12 | * 13 | * Input: 14 | * board = [ 15 | * ['o','a','a','n'], 16 | * ['e','t','a','e'], 17 | * ['i','h','k','r'], 18 | * ['i','f','l','v'] 19 | * ] 20 | * words = ["oath","pea","eat","rain"] 21 | * 22 | * Output: ["eat","oath"] 23 | * 24 | * 25 | * 26 | * 27 | * Note: 28 | * 29 | *
    30 | * All inputs are consist of lowercase letters a-z. 31 | * The values of words are distinct. 32 | *
33 | * 34 | */ 35 | pub struct Solution {} 36 | 37 | // problem: https://leetcode.com/problems/word-search-ii/ 38 | // discuss: https://leetcode.com/problems/word-search-ii/discuss/?currentPage=1&orderBy=most_votes&query= 39 | 40 | // submission codes start here 41 | // TODO 42 | 43 | impl Solution { 44 | pub fn find_words(board: Vec>, words: Vec) -> Vec { 45 | vec![] 46 | } 47 | } 48 | 49 | // submission codes end 50 | 51 | #[cfg(test)] 52 | mod tests { 53 | use super::*; 54 | 55 | #[test] 56 | fn test_212() {} 57 | } 58 | -------------------------------------------------------------------------------- /src/solution/s0214_shortest_palindrome.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [214] Shortest Palindrome 3 | * 4 | * Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: "aacecaaa" 10 | * Output: "aaacecaaa" 11 | * 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: "abcd" 17 | * Output: "dcbabcd" 18 | */ 19 | pub struct Solution {} 20 | 21 | // problem: https://leetcode.com/problems/shortest-palindrome/ 22 | // discuss: https://leetcode.com/problems/shortest-palindrome/discuss/?currentPage=1&orderBy=most_votes&query= 23 | 24 | // submission codes start here 25 | 26 | impl Solution { 27 | pub fn shortest_palindrome(s: String) -> String { 28 | "".to_owned() 29 | } 30 | } 31 | 32 | // submission codes end 33 | 34 | #[cfg(test)] 35 | mod tests { 36 | use super::*; 37 | 38 | #[test] 39 | fn test_214() {} 40 | } 41 | -------------------------------------------------------------------------------- /src/solution/s0215_kth_largest_element_in_an_array.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [215] Kth Largest Element in an Array 3 | * 4 | * Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: [3,2,1,5,6,4] and k = 2 10 | * Output: 5 11 | * 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: [3,2,3,1,2,4,5,5,6] and k = 4 17 | * Output: 4 18 | * 19 | * Note:
20 | * You may assume k is always valid, 1 ≤ k ≤ array's length. 21 | * 22 | */ 23 | pub struct Solution {} 24 | 25 | // problem: https://leetcode.com/problems/kth-largest-element-in-an-array/ 26 | // discuss: https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/?currentPage=1&orderBy=most_votes&query= 27 | 28 | // submission codes start here 29 | 30 | use std::cmp::Reverse; 31 | use std::collections::BinaryHeap; 32 | impl Solution { 33 | pub fn find_kth_largest(nums: Vec, k: i32) -> i32 { 34 | let k = k as usize; 35 | let mut heap = BinaryHeap::with_capacity(k); 36 | for &num in nums.iter() { 37 | if heap.len() < k as usize { 38 | heap.push(Reverse(num)) 39 | } else if num >= heap.peek().unwrap().0 { 40 | heap.pop(); 41 | heap.push(Reverse(num)); 42 | } 43 | } 44 | heap.peek().unwrap().0 45 | } 46 | } 47 | 48 | // submission codes end 49 | 50 | #[cfg(test)] 51 | mod tests { 52 | use super::*; 53 | 54 | #[test] 55 | fn test_215() { 56 | assert_eq!( 57 | Solution::find_kth_largest(vec![3, 2, 3, 1, 2, 4, 5, 5, 6], 4), 58 | 4 59 | ); 60 | assert_eq!(Solution::find_kth_largest(vec![3, 2, 1, 5, 6, 4], 2), 5); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/solution/s0216_combination_sum_iii.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [216] Combination Sum III 3 | * 4 | *
5 | * Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. 6 | * 7 | * Note: 8 | * 9 | * 10 | * All numbers will be positive integers. 11 | * The solution set must not contain duplicate combinations. 12 | * 13 | * 14 | * Example 1: 15 | * 16 | * 17 | * Input: k = 3, n = 7 18 | * Output: [[1,2,4]] 19 | * 20 | * 21 | * Example 2: 22 | * 23 | * 24 | * Input: k = 3, n = 9 25 | * Output: [[1,2,6], [1,3,5], [2,3,4]] 26 | * 27 | *
28 | */ 29 | pub struct Solution {} 30 | 31 | // problem: https://leetcode.com/problems/combination-sum-iii/ 32 | // discuss: https://leetcode.com/problems/combination-sum-iii/discuss/?currentPage=1&orderBy=most_votes&query= 33 | 34 | // submission codes start here 35 | 36 | impl Solution { 37 | pub fn combination_sum3(k: i32, n: i32) -> Vec> { 38 | if k > 9 || k < 1 { 39 | return vec![]; 40 | } 41 | let max = (0..k).fold(0, |acc, t| acc + 9 - t); 42 | let min = (0..k).fold(0, |acc, t| acc + t); 43 | if n < min || n > max { 44 | return vec![]; 45 | } 46 | let mut res = Vec::new(); 47 | let mut seed = Vec::new(); 48 | Solution::helper(n, 0, k, seed, &mut res); 49 | res 50 | } 51 | 52 | fn helper(distance: i32, prev: i32, remain: i32, mut curr: Vec, res: &mut Vec>) { 53 | if remain == 0 { 54 | if distance == 0 { 55 | res.push(curr); 56 | } 57 | return; 58 | } 59 | for i in (prev + 1..=9) { 60 | if distance - i < 0 { 61 | break; 62 | } 63 | let mut new_vec = curr.clone(); 64 | new_vec.push(i); 65 | Solution::helper(distance - i, i, remain - 1, new_vec, res); 66 | } 67 | } 68 | } 69 | 70 | // submission codes end 71 | 72 | #[cfg(test)] 73 | mod tests { 74 | use super::*; 75 | 76 | #[test] 77 | fn test_216() { 78 | assert_eq!( 79 | Solution::combination_sum3(3, 9), 80 | vec![vec![1, 2, 6], vec![1, 3, 5], vec![2, 3, 4]] 81 | ); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/solution/s0217_contains_duplicate.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [217] Contains Duplicate 3 | * 4 | * Given an array of integers, find if the array contains any duplicates. 5 | * 6 | * Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 7 | * 8 | * Example 1: 9 | * 10 | * 11 | * Input: [1,2,3,1] 12 | * Output: true 13 | * 14 | * Example 2: 15 | * 16 | * 17 | * Input: [1,2,3,4] 18 | * Output: false 19 | * 20 | * Example 3: 21 | * 22 | * 23 | * Input: [1,1,1,3,3,4,3,2,4,2] 24 | * Output: true 25 | * 26 | */ 27 | pub struct Solution {} 28 | 29 | // problem: https://leetcode.com/problems/contains-duplicate/ 30 | // discuss: https://leetcode.com/problems/contains-duplicate/discuss/?currentPage=1&orderBy=most_votes&query= 31 | 32 | // submission codes start here 33 | 34 | impl Solution { 35 | pub fn contains_duplicate(nums: Vec) -> bool { 36 | if nums.is_empty() { 37 | return false; 38 | } 39 | let mut nums = nums; 40 | nums.sort_unstable(); 41 | let mut prev = nums[0]; 42 | for i in 1..nums.len() { 43 | if nums[i] == prev { 44 | return true; 45 | } 46 | prev = nums[i] 47 | } 48 | false 49 | } 50 | } 51 | 52 | // submission codes end 53 | 54 | #[cfg(test)] 55 | mod tests { 56 | use super::*; 57 | 58 | #[test] 59 | fn test_217() { 60 | assert_eq!(Solution::contains_duplicate(vec![1]), false); 61 | assert_eq!(Solution::contains_duplicate(vec![]), false); 62 | assert_eq!(Solution::contains_duplicate(vec![1, 2, 3, 4]), false); 63 | assert_eq!(Solution::contains_duplicate(vec![1, 2, 3, 1]), true); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/solution/s0219_contains_duplicate_ii.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [219] Contains Duplicate II 3 | * 4 | * Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 5 | * 6 | *
7 | * Example 1: 8 | * 9 | * 10 | * Input: nums = [1,2,3,1], k = 3 11 | * Output: true 12 | * 13 | * 14 | *
15 | * Example 2: 16 | * 17 | * 18 | * Input: nums = [1,0,1,1], k = 1 19 | * Output: true 20 | * 21 | * 22 | *
23 | * Example 3: 24 | * 25 | * 26 | * Input: nums = [1,2,3,1,2,3], k = 2 27 | * Output: false 28 | * 29 | *
30 | *
31 | *
32 | * 33 | */ 34 | pub struct Solution {} 35 | 36 | // problem: https://leetcode.com/problems/contains-duplicate-ii/ 37 | // discuss: https://leetcode.com/problems/contains-duplicate-ii/discuss/?currentPage=1&orderBy=most_votes&query= 38 | 39 | // submission codes start here 40 | 41 | use std::collections::HashMap; 42 | impl Solution { 43 | pub fn contains_nearby_duplicate(nums: Vec, k: i32) -> bool { 44 | let mut map = HashMap::new(); 45 | for (idx, &num) in nums.iter().enumerate() { 46 | match map.get(&num) { 47 | Some(v) => { 48 | if idx - v <= k as usize { 49 | return true; 50 | } 51 | map.insert(num, idx); 52 | } 53 | None => { 54 | map.insert(num, idx); 55 | } 56 | } 57 | } 58 | false 59 | } 60 | } 61 | 62 | // submission codes end 63 | 64 | #[cfg(test)] 65 | mod tests { 66 | use super::*; 67 | 68 | #[test] 69 | fn test_219() { 70 | assert_eq!( 71 | Solution::contains_nearby_duplicate(vec![1, 2, 3, 1, 2, 3], 2), 72 | false 73 | ); 74 | assert_eq!( 75 | Solution::contains_nearby_duplicate(vec![1, 2, 3, 1, 2, 3], 3), 76 | true 77 | ); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/solution/s0226_invert_binary_tree.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [226] Invert Binary Tree 3 | * 4 | * Invert a binary tree. 5 | * 6 | * Example: 7 | * 8 | * Input: 9 | * 10 | * 11 | * 4 12 | * / \ 13 | * 2 7 14 | * / \ / \ 15 | * 1 3 6 9 16 | * 17 | * Output: 18 | * 19 | * 20 | * 4 21 | * / \ 22 | * 7 2 23 | * / \ / \ 24 | * 9 6 3 1 25 | * 26 | * Trivia:
27 | * This problem was inspired by this original tweet by Max Howell: 28 | * 29 | *
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.
30 | * 31 | */ 32 | pub struct Solution {} 33 | use crate::util::tree::{to_tree, TreeNode}; 34 | 35 | // problem: https://leetcode.com/problems/invert-binary-tree/ 36 | // discuss: https://leetcode.com/problems/invert-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= 37 | 38 | // submission codes start here 39 | 40 | use std::cell::RefCell; 41 | use std::rc::Rc; 42 | impl Solution { 43 | pub fn invert_tree(root: Option>>) -> Option>> { 44 | if let Some(node) = root.clone() { 45 | Solution::invert_tree(node.borrow().right.clone()); 46 | Solution::invert_tree(node.borrow().left.clone()); 47 | let left = node.borrow().left.clone(); 48 | let right = node.borrow().right.clone(); 49 | node.borrow_mut().left = right; 50 | node.borrow_mut().right = left; 51 | } 52 | root 53 | } 54 | } 55 | 56 | // submission codes end 57 | 58 | #[cfg(test)] 59 | mod tests { 60 | use super::*; 61 | 62 | #[test] 63 | fn test_226() { 64 | assert_eq!( 65 | Solution::invert_tree(tree![4, 2, 7, 1, 3, 6, 9]), 66 | tree![4, 7, 2, 9, 6, 3, 1] 67 | ); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/solution/s0228_summary_ranges.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [228] Summary Ranges 3 | * 4 | * Given a sorted integer array without duplicates, return the summary of its ranges. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: [0,1,2,4,5,7] 10 | * Output: ["0->2","4->5","7"] 11 | * Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range. 12 | * 13 | * 14 | * Example 2: 15 | * 16 | * 17 | * Input: [0,2,3,4,6,8,9] 18 | * Output: ["0","2->4","6","8->9"] 19 | * Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range. 20 | * 21 | * 22 | */ 23 | pub struct Solution {} 24 | 25 | // problem: https://leetcode.com/problems/summary-ranges/ 26 | // discuss: https://leetcode.com/problems/summary-ranges/discuss/?currentPage=1&orderBy=most_votes&query= 27 | 28 | // submission codes start here 29 | 30 | impl Solution { 31 | pub fn summary_ranges(nums: Vec) -> Vec { 32 | if nums.is_empty() { 33 | return vec![]; 34 | } 35 | let mut res = Vec::new(); 36 | let mut curr = nums[0]; 37 | let mut start = nums[0]; 38 | for num in nums.into_iter().skip(1) { 39 | if num == curr + 1 { 40 | curr = num; 41 | } else { 42 | // seq done 43 | Solution::record(&mut res, start, curr); 44 | start = num; 45 | curr = num; 46 | } 47 | } 48 | Solution::record(&mut res, start, curr); 49 | res 50 | } 51 | 52 | pub fn record(vec: &mut Vec, start: i32, end: i32) { 53 | if start == end { 54 | vec.push(format!("{}", start)) 55 | } else { 56 | vec.push(format!("{}->{}", start, end)) 57 | } 58 | } 59 | } 60 | 61 | // submission codes end 62 | 63 | #[cfg(test)] 64 | mod tests { 65 | use super::*; 66 | 67 | #[test] 68 | fn test_228() { 69 | assert_eq!( 70 | Solution::summary_ranges(vec![0, 1, 2, 3, 4, 5, 6]), 71 | vec_string!["0->6"] 72 | ); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/solution/s0231_power_of_two.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [231] Power of Two 3 | * 4 | * Given an integer, write a function to determine if it is a power of two. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: 1 10 | * Output: true 11 | * Explanation: 2^0 = 1 12 | * 13 | * 14 | * Example 2: 15 | * 16 | * 17 | * Input: 16 18 | * Output: true 19 | * Explanation: 2^4 = 16 20 | * 21 | * Example 3: 22 | * 23 | * 24 | * Input: 218 25 | * Output: false 26 | * 27 | */ 28 | pub struct Solution {} 29 | 30 | // problem: https://leetcode.com/problems/power-of-two/ 31 | // discuss: https://leetcode.com/problems/power-of-two/discuss/?currentPage=1&orderBy=most_votes&query= 32 | 33 | // submission codes start here 34 | 35 | impl Solution { 36 | pub fn is_power_of_two(n: i32) -> bool { 37 | let results: Vec = (0..31).map(|x| 2_i32.pow(x)).collect(); 38 | results.binary_search(&n).is_ok() 39 | } 40 | } 41 | 42 | // submission codes end 43 | 44 | #[cfg(test)] 45 | mod tests { 46 | use super::*; 47 | 48 | #[test] 49 | fn test_231() { 50 | assert_eq!(Solution::is_power_of_two(-1), false); 51 | assert_eq!(Solution::is_power_of_two(1), true); 52 | assert_eq!(Solution::is_power_of_two(1024), true); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/solution/s0233_number_of_digit_one.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [233] Number of Digit One 3 | * 4 | * Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: 13 10 | * Output: 6 11 | * Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. 12 | * 13 | * 14 | */ 15 | pub struct Solution {} 16 | 17 | // problem: https://leetcode.com/problems/number-of-digit-one/ 18 | // discuss: https://leetcode.com/problems/number-of-digit-one/discuss/?currentPage=1&orderBy=most_votes&query= 19 | 20 | // submission codes start here 21 | 22 | impl Solution { 23 | pub fn count_digit_one(n: i32) -> i32 { 24 | 0 25 | } 26 | } 27 | 28 | // submission codes end 29 | 30 | #[cfg(test)] 31 | mod tests { 32 | use super::*; 33 | 34 | #[test] 35 | fn test_233() {} 36 | } 37 | -------------------------------------------------------------------------------- /src/solution/s0238_product_of_array_except_self.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [238] Product of Array Except Self 3 | * 4 | * Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: [1,2,3,4] 10 | * Output: [24,12,8,6] 11 | * 12 | * 13 | * Note: Please solve it without division and in O(n). 14 | * 15 | * Follow up:
16 | * Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) 17 | * 18 | */ 19 | pub struct Solution {} 20 | 21 | // problem: https://leetcode.com/problems/product-of-array-except-self/ 22 | // discuss: https://leetcode.com/problems/product-of-array-except-self/discuss/?currentPage=1&orderBy=most_votes&query= 23 | 24 | // submission codes start here 25 | 26 | /* 27 | x 2 3 4 = 24 28 | 1 x 3 4 = 12 29 | 1 2 x 4 = 8 30 | 1 2 3 x = 6 31 | */ 32 | impl Solution { 33 | pub fn product_except_self(nums: Vec) -> Vec { 34 | if nums.len() < 2 { 35 | return vec![]; 36 | } 37 | let mut res = vec![1; nums.len()]; 38 | let mut n = 1; 39 | for i in (0..nums.len() - 1).rev() { 40 | n *= nums[i + 1]; 41 | res[i] = n; 42 | } 43 | n = 1; 44 | for i in 1..nums.len() { 45 | n *= nums[i - 1]; 46 | res[i] *= n; 47 | } 48 | res 49 | } 50 | } 51 | 52 | // submission codes end 53 | 54 | #[cfg(test)] 55 | mod tests { 56 | use super::*; 57 | 58 | #[test] 59 | fn test_238() { 60 | assert_eq!( 61 | Solution::product_except_self(vec![1, 2, 3, 4]), 62 | vec![24, 12, 8, 6] 63 | ); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/solution/s0242_valid_anagram.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [242] Valid Anagram 3 | * 4 | * Given two strings s and t , write a function to determine if t is an anagram of s. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: s = "anagram", t = "nagaram" 10 | * Output: true 11 | * 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: s = "rat", t = "car" 17 | * Output: false 18 | * 19 | * 20 | * Note:
21 | * You may assume the string contains only lowercase alphabets. 22 | * 23 | * Follow up:
24 | * What if the inputs contain unicode characters? How would you adapt your solution to such case? 25 | * 26 | */ 27 | pub struct Solution {} 28 | 29 | // problem: https://leetcode.com/problems/valid-anagram/ 30 | // discuss: https://leetcode.com/problems/valid-anagram/discuss/?currentPage=1&orderBy=most_votes&query= 31 | 32 | // submission codes start here 33 | 34 | impl Solution { 35 | pub fn is_anagram(s: String, t: String) -> bool { 36 | Solution::hit(s) == Solution::hit(t) 37 | } 38 | 39 | fn hit(s: String) -> Vec { 40 | let mut hit = vec![0; 27]; 41 | for ch in s.chars() { 42 | hit[(ch as u8 - 'a' as u8) as usize] += 1; 43 | } 44 | hit 45 | } 46 | } 47 | 48 | // submission codes end 49 | 50 | #[cfg(test)] 51 | mod tests { 52 | use super::*; 53 | 54 | #[test] 55 | fn test_242() { 56 | assert_eq!( 57 | Solution::is_anagram("anagram".to_owned(), "nagaram".to_owned()), 58 | true 59 | ); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/solution/s0257_binary_tree_paths.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [257] Binary Tree Paths 3 | * 4 | * Given a binary tree, return all root-to-leaf paths. 5 | * 6 | * Note: A leaf is a node with no children. 7 | * 8 | * Example: 9 | * 10 | * 11 | * Input: 12 | * 13 | * 1 14 | * / \ 15 | * 2 3 16 | * \ 17 | * 5 18 | * 19 | * Output: ["1->2->5", "1->3"] 20 | * 21 | * Explanation: All root-to-leaf paths are: 1->2->5, 1->3 22 | * 23 | */ 24 | pub struct Solution {} 25 | use crate::util::tree::{to_tree, TreeNode}; 26 | 27 | // problem: https://leetcode.com/problems/binary-tree-paths/ 28 | // discuss: https://leetcode.com/problems/binary-tree-paths/discuss/?currentPage=1&orderBy=most_votes&query= 29 | 30 | // submission codes start here 31 | 32 | // Definition for a binary tree node. 33 | // #[derive(Debug, PartialEq, Eq)] 34 | // pub struct TreeNode { 35 | // pub val: i32, 36 | // pub left: Option>>, 37 | // pub right: Option>>, 38 | // } 39 | // 40 | // impl TreeNode { 41 | // #[inline] 42 | // pub fn new(val: i32) -> Self { 43 | // TreeNode { 44 | // val, 45 | // left: None, 46 | // right: None 47 | // } 48 | // } 49 | // } 50 | use std::cell::RefCell; 51 | use std::rc::Rc; 52 | impl Solution { 53 | pub fn binary_tree_paths(root: Option>>) -> Vec { 54 | let mut res = Vec::new(); 55 | Solution::helper(root, "".to_owned(), &mut res); 56 | res 57 | } 58 | 59 | fn helper(root: Option>>, path: String, res: &mut Vec) { 60 | if let Some(inner) = root { 61 | if inner.borrow().left.is_none() && inner.borrow().right.is_none() { 62 | res.push(format!("{}{}", path, inner.borrow().val)); 63 | } else { 64 | let path = format!("{}{}->", path, inner.borrow().val); 65 | Solution::helper(inner.borrow().left.clone(), path.clone(), res); 66 | Solution::helper(inner.borrow().right.clone(), path, res); 67 | } 68 | } 69 | } 70 | } 71 | 72 | // submission codes end 73 | 74 | #[cfg(test)] 75 | mod tests { 76 | use super::*; 77 | 78 | #[test] 79 | fn test_257() { 80 | assert_eq!( 81 | Solution::binary_tree_paths(tree![1, 2, 3, null, 5]), 82 | vec_string!["1->2->5", "1->3"] 83 | ); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/solution/s0258_add_digits.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [258] Add Digits 3 | * 4 | * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: 38 10 | * Output: 2 11 | * Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 12 | * Since 2 has only one digit, return it. 13 | * 14 | * 15 | * Follow up:
16 | * Could you do it without any loop/recursion in O(1) runtime? 17 | */ 18 | pub struct Solution {} 19 | 20 | // problem: https://leetcode.com/problems/add-digits/ 21 | // discuss: https://leetcode.com/problems/add-digits/discuss/?currentPage=1&orderBy=most_votes&query= 22 | 23 | // submission codes start here 24 | 25 | impl Solution { 26 | pub fn add_digits(num: i32) -> i32 { 27 | 1 + ((num - 1) % 9) 28 | } 29 | } 30 | 31 | // submission codes end 32 | 33 | #[cfg(test)] 34 | mod tests { 35 | use super::*; 36 | 37 | #[test] 38 | fn test_258() { 39 | assert_eq!(Solution::add_digits(1234), 1); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/solution/s0260_single_number_iii.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [260] Single Number III 3 | * 4 | * Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: [1,2,1,3,2,5] 10 | * Output: [3,5] 11 | * 12 | * Note: 13 | * 14 | *
    15 | * The order of the result is not important. So in the above example, [5, 3] is also correct. 16 | * Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? 17 | *
18 | */ 19 | pub struct Solution {} 20 | 21 | // problem: https://leetcode.com/problems/single-number-iii/ 22 | // discuss: https://leetcode.com/problems/single-number-iii/discuss/?currentPage=1&orderBy=most_votes&query= 23 | 24 | // submission codes start here 25 | 26 | impl Solution { 27 | pub fn single_number(nums: Vec) -> Vec { 28 | let mut res = 0; 29 | for &num in nums.iter() { 30 | res = res ^ num; 31 | } 32 | let right_most_set_bit = res & !(res - 1); 33 | let mut bit_set = 0; 34 | let mut bit_unset = 0; 35 | for &num in nums.iter() { 36 | if num & right_most_set_bit == 0 { 37 | bit_unset = bit_unset ^ num; 38 | } else { 39 | bit_set = bit_set ^ num; 40 | } 41 | } 42 | return vec![bit_set, bit_unset]; 43 | } 44 | } 45 | 46 | // submission codes end 47 | 48 | #[cfg(test)] 49 | mod tests { 50 | use super::*; 51 | 52 | #[test] 53 | fn test_260() { 54 | assert_eq!(Solution::single_number(vec![1, 2, 1, 2, 3, 4]), vec![3, 4]); 55 | assert_eq!(Solution::single_number(vec![1, 2, 1, 3, 2, 5]), vec![3, 5]); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/solution/s0263_ugly_number.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [263] Ugly Number 3 | * 4 | * Write a program to check whether a given number is an ugly number. 5 | * 6 | * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 7 | * 8 | * Example 1: 9 | * 10 | * 11 | * Input: 6 12 | * Output: true 13 | * Explanation: 6 = 2 × 3 14 | * 15 | * Example 2: 16 | * 17 | * 18 | * Input: 8 19 | * Output: true 20 | * Explanation: 8 = 2 × 2 × 2 21 | * 22 | * 23 | * Example 3: 24 | * 25 | * 26 | * Input: 14 27 | * Output: false 28 | * Explanation: 14 is not ugly since it includes another prime factor 7. 29 | * 30 | * 31 | * Note: 32 | * 33 | *
    34 | * 1 is typically treated as an ugly number. 35 | * Input is within the 32-bit signed integer range: [-2^31, 2^31 - 1]. 36 | *
37 | */ 38 | pub struct Solution {} 39 | 40 | // problem: https://leetcode.com/problems/ugly-number/ 41 | // discuss: https://leetcode.com/problems/ugly-number/discuss/?currentPage=1&orderBy=most_votes&query= 42 | 43 | // submission codes start here 44 | 45 | impl Solution { 46 | pub fn is_ugly(num: i32) -> bool { 47 | if num <= 0 { 48 | false 49 | } else if num == 1 { 50 | true 51 | } else if num % 5 == 0 { 52 | Solution::is_ugly(num / 5) 53 | } else if num % 3 == 0 { 54 | Solution::is_ugly(num / 3) 55 | } else if num % 2 == 0 { 56 | Solution::is_ugly(num / 2) 57 | } else { 58 | false 59 | } 60 | } 61 | } 62 | 63 | // submission codes end 64 | 65 | #[cfg(test)] 66 | mod tests { 67 | use super::*; 68 | 69 | #[test] 70 | fn test_263() { 71 | assert_eq!(Solution::is_ugly(25), true); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/solution/s0264_ugly_number_ii.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [264] Ugly Number II 3 | * 4 | * Write a program to find the n-th ugly number. 5 | * 6 | * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 7 | * 8 | * Example: 9 | * 10 | * 11 | * Input: n = 10 12 | * Output: 12 13 | * Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. 14 | * 15 | * Note: 16 | * 17 | *
    18 | * 1 is typically treated as an ugly number. 19 | * n does not exceed 1690. 20 | *
21 | */ 22 | pub struct Solution {} 23 | 24 | // problem: https://leetcode.com/problems/ugly-number-ii/ 25 | // discuss: https://leetcode.com/problems/ugly-number-ii/discuss/?currentPage=1&orderBy=most_votes&query= 26 | 27 | // submission codes start here 28 | 29 | impl Solution { 30 | pub fn nth_ugly_number(n: i32) -> i32 { 31 | let mut base2 = 0; 32 | let mut base3 = 0; 33 | let mut base5 = 0; 34 | let mut ugly = vec![1; 1]; 35 | for _ in 1..n { 36 | let next2 = ugly[base2] * 2; 37 | let next3 = ugly[base3] * 3; 38 | let next5 = ugly[base5] * 5; 39 | let next = i32::min(next2, i32::min(next3, next5)); 40 | if next2 == next { 41 | base2 += 1 42 | } 43 | if next3 == next { 44 | base3 += 1 45 | } 46 | if next5 == next { 47 | base5 += 1 48 | } 49 | ugly.push(next) 50 | } 51 | *ugly.last().unwrap() 52 | } 53 | } 54 | 55 | // submission codes end 56 | 57 | #[cfg(test)] 58 | mod tests { 59 | use super::*; 60 | 61 | #[test] 62 | fn test_264() { 63 | assert_eq!(Solution::nth_ugly_number(1), 1); 64 | assert_eq!(Solution::nth_ugly_number(10), 12); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/solution/s0268_missing_number.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [268] Missing Number 3 | * 4 | * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: [3,0,1] 10 | * Output: 2 11 | * 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: [9,6,4,2,3,5,7,0,1] 17 | * Output: 8 18 | * 19 | * 20 | * Note:
21 | * Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? 22 | */ 23 | pub struct Solution {} 24 | 25 | // problem: https://leetcode.com/problems/missing-number/ 26 | // discuss: https://leetcode.com/problems/missing-number/discuss/?currentPage=1&orderBy=most_votes&query= 27 | 28 | // submission codes start here 29 | 30 | impl Solution { 31 | pub fn missing_number(nums: Vec) -> i32 { 32 | ((nums.len() + 1) * nums.len()) as i32 / 2 - nums.into_iter().fold(0, |acc, v| acc + v) 33 | } 34 | } 35 | 36 | // submission codes end 37 | 38 | #[cfg(test)] 39 | mod tests { 40 | use super::*; 41 | 42 | #[test] 43 | fn test_268() { 44 | assert_eq!(Solution::missing_number(vec![3, 0, 1]), 2); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/solution/s0273_integer_to_english_words.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [273] Integer to English Words 3 | * 4 | * Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 1. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: 123 10 | * Output: "One Hundred Twenty Three" 11 | * 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: 12345 17 | * Output: "Twelve Thousand Three Hundred Forty Five" 18 | * 19 | * Example 3: 20 | * 21 | * 22 | * Input: 1234567 23 | * Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" 24 | * 25 | * 26 | * Example 4: 27 | * 28 | * 29 | * Input: 1234567891 30 | * Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One" 31 | * 32 | * 33 | */ 34 | pub struct Solution {} 35 | 36 | // problem: https://leetcode.com/problems/integer-to-english-words/ 37 | // discuss: https://leetcode.com/problems/integer-to-english-words/discuss/?currentPage=1&orderBy=most_votes&query= 38 | 39 | // submission codes start here 40 | 41 | // static digits: Vec<&str> = vec!["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]; 42 | // static xteens: Vec<&str> = vec!["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventenn", "Eighteen", "Nineteen"]; 43 | // static xtys: Vec<&str> = vec!["Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]; 44 | // static hunderd: &str = "Hunderd"; 45 | // static thousands: Vec<&str> = vec!["Thousand", "Million", "Billion"]; 46 | 47 | impl Solution { 48 | pub fn number_to_words(num: i32) -> String { 49 | "".to_owned() 50 | } 51 | } 52 | 53 | // submission codes end 54 | 55 | #[cfg(test)] 56 | mod tests { 57 | use super::*; 58 | 59 | #[test] 60 | fn test_273() {} 61 | } 62 | -------------------------------------------------------------------------------- /src/solution/s0274_h_index.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [274] H-Index 3 | * 4 | * Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. 5 | * 6 | * According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N - h papers have no more than h citations each." 7 | * 8 | * Example: 9 | * 10 | * 11 | * Input: citations = [3,0,6,1,5] 12 | * Output: 3 13 | * Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had 14 | * received 3, 0, 6, 1, 5 citations respectively. 15 | * Since the researcher has 3 papers with at least 3 citations each and the remaining 16 | * two with no more than 3 citations each, her h-index is 3. 17 | * 18 | * Note: If there are several possible values for h, the maximum one is taken as the h-index. 19 | * 20 | */ 21 | pub struct Solution {} 22 | 23 | // problem: https://leetcode.com/problems/h-index/ 24 | // discuss: https://leetcode.com/problems/h-index/discuss/?currentPage=1&orderBy=most_votes&query= 25 | 26 | // submission codes start here 27 | 28 | impl Solution { 29 | pub fn h_index(mut citations: Vec) -> i32 { 30 | citations.sort_unstable(); 31 | let mut hidx = 0; 32 | for &v in citations.iter().rev() { 33 | if v >= hidx + 1 { 34 | hidx += 1; 35 | } else { 36 | break; 37 | } 38 | } 39 | hidx 40 | } 41 | } 42 | 43 | // submission codes end 44 | 45 | #[cfg(test)] 46 | mod tests { 47 | use super::*; 48 | 49 | #[test] 50 | fn test_274() { 51 | assert_eq!(Solution::h_index(vec![3, 0, 6, 1, 5]), 3); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/solution/s0279_perfect_squares.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [279] Perfect Squares 3 | * 4 | * Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: n = 12 10 | * Output: 3 11 | * Explanation: 12 = 4 + 4 + 4. 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: n = 13 17 | * Output: 2 18 | * Explanation: 13 = 4 + 9. 19 | */ 20 | pub struct Solution {} 21 | 22 | // problem: https://leetcode.com/problems/perfect-squares/ 23 | // discuss: https://leetcode.com/problems/perfect-squares/discuss/?currentPage=1&orderBy=most_votes&query= 24 | 25 | // submission codes start here 26 | 27 | // BFS 28 | use std::collections::VecDeque; 29 | impl Solution { 30 | pub fn num_squares(n: i32) -> i32 { 31 | if n < 1 { 32 | return 0; 33 | } 34 | let mut deq = VecDeque::new(); 35 | deq.push_back((1, n)); 36 | while let Some((level, num)) = deq.pop_front() { 37 | let mut base = 1; 38 | while base * base <= num { 39 | if base * base == num { 40 | return level; 41 | } 42 | deq.push_back((level + 1, num - base * base)); 43 | base += 1; 44 | } 45 | } 46 | 0 47 | } 48 | } 49 | 50 | // submission codes end 51 | 52 | #[cfg(test)] 53 | mod tests { 54 | use super::*; 55 | 56 | #[test] 57 | fn test_279() { 58 | assert_eq!(Solution::num_squares(13), 2); 59 | assert_eq!(Solution::num_squares(12), 3); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/solution/s0282_expression_add_operators.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [282] Expression Add Operators 3 | * 4 | * Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: num = "123", target = 6 10 | * Output: ["1+2+3", "1*2*3"] 11 | * 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: num = "232", target = 8 17 | * Output: ["2*3+2", "2+3*2"] 18 | * 19 | * Example 3: 20 | * 21 | * 22 | * Input: num = "105", target = 5 23 | * Output: ["1*0+5","10-5"] 24 | * 25 | * Example 4: 26 | * 27 | * 28 | * Input: num = "00", target = 0 29 | * Output: ["0+0", "0-0", "0*0"] 30 | * 31 | * 32 | * Example 5: 33 | * 34 | * 35 | * Input: num = "3456237490", target = 9191 36 | * Output: [] 37 | * 38 | * 39 | */ 40 | pub struct Solution {} 41 | 42 | // problem: https://leetcode.com/problems/expression-add-operators/ 43 | // discuss: https://leetcode.com/problems/expression-add-operators/discuss/?currentPage=1&orderBy=most_votes&query= 44 | 45 | // submission codes start here 46 | 47 | impl Solution { 48 | pub fn add_operators(num: String, target: i32) -> Vec { 49 | vec![] 50 | } 51 | } 52 | 53 | // submission codes end 54 | 55 | #[cfg(test)] 56 | mod tests { 57 | use super::*; 58 | 59 | #[test] 60 | fn test_282() {} 61 | } 62 | -------------------------------------------------------------------------------- /src/solution/s0283_move_zeroes.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [283] Move Zeroes 3 | * 4 | * Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: [0,1,0,3,12] 10 | * Output: [1,3,12,0,0] 11 | * 12 | * Note: 13 | * 14 | *
    15 | * You must do this in-place without making a copy of the array. 16 | * Minimize the total number of operations. 17 | *
18 | */ 19 | pub struct Solution {} 20 | 21 | // problem: https://leetcode.com/problems/move-zeroes/ 22 | // discuss: https://leetcode.com/problems/move-zeroes/discuss/?currentPage=1&orderBy=most_votes&query= 23 | 24 | // submission codes start here 25 | 26 | impl Solution { 27 | pub fn move_zeroes(nums: &mut Vec) { 28 | let mut last_none_zero = 0_usize; 29 | for i in 0..nums.len() { 30 | if nums[i] != 0 { 31 | nums.swap(last_none_zero, i); 32 | last_none_zero += 1; 33 | } 34 | } 35 | } 36 | } 37 | 38 | // submission codes end 39 | 40 | #[cfg(test)] 41 | mod tests { 42 | use super::*; 43 | 44 | #[test] 45 | fn test_283() { 46 | let mut vec = vec![0, 1, 0, 3, 12]; 47 | Solution::move_zeroes(&mut vec); 48 | assert_eq!(vec, vec![1, 3, 12, 0, 0]); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/solution/s0287_find_the_duplicate_number.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [287] Find the Duplicate Number 3 | * 4 | * Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. 5 | * 6 | * Example 1: 7 | * 8 | * 9 | * Input: [1,3,4,2,2] 10 | * Output: 2 11 | * 12 | * 13 | * Example 2: 14 | * 15 | * 16 | * Input: [3,1,3,4,2] 17 | * Output: 3 18 | * 19 | * Note: 20 | * 21 | *
    22 | * You must not modify the array (assume the array is read only). 23 | * You must use only constant, O(1) extra space. 24 | * Your runtime complexity should be less than O(n^2). 25 | * There is only one duplicate number in the array, but it could be repeated more than once. 26 | *
27 | * 28 | */ 29 | pub struct Solution {} 30 | 31 | // problem: https://leetcode.com/problems/find-the-duplicate-number/ 32 | // discuss: https://leetcode.com/problems/find-the-duplicate-number/discuss/?currentPage=1&orderBy=most_votes&query= 33 | 34 | // submission codes start here 35 | 36 | // 假如把值看做 next node 的下标, 那么: 37 | // 从 0 出发不会回到 0 38 | // 一定有环, 因为 1-n 全部落在下标范围 [0, n] 中 39 | // 从 0 遍历经过的环中, 一定存在重复数字 x, 且 x 就是入环点的下标: 40 | // 1.从 0 走到入环点, 入环点的前驱值为 x; 2.入环点在环上的前驱值也是 x 41 | // 由于我们不可能回到 0, 因此这两个节点下标不同, x 即为要找的重复数字 42 | impl Solution { 43 | pub fn find_duplicate(nums: Vec) -> i32 { 44 | let mut slow: usize = nums[0] as usize; 45 | let mut fast: usize = nums[nums[0] as usize] as usize; 46 | // util slow meet fast 47 | while slow != fast { 48 | slow = nums[slow] as usize; 49 | fast = nums[nums[fast] as usize] as usize; 50 | } 51 | 52 | fast = 0_usize; 53 | while slow != fast { 54 | fast = nums[fast] as usize; 55 | slow = nums[slow] as usize; 56 | } 57 | slow as i32 58 | } 59 | } 60 | 61 | // submission codes end 62 | 63 | #[cfg(test)] 64 | mod tests { 65 | use super::*; 66 | 67 | #[test] 68 | fn test_287() { 69 | assert_eq!(Solution::find_duplicate(vec![1, 3, 4, 2, 2]), 2); 70 | assert_eq!(Solution::find_duplicate(vec![3, 1, 3, 4, 2]), 3); 71 | assert_eq!(Solution::find_duplicate(vec![1, 2, 3, 4, 5, 5]), 5); 72 | assert_eq!(Solution::find_duplicate(vec![5, 1, 2, 3, 4, 5]), 5); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/solution/s0292_nim_game.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [292] Nim Game 3 | * 4 | * You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 5 | * 6 | * Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. 7 | * 8 | * Example: 9 | * 10 | * 11 | * Input: 4 12 | * Output: false 13 | * Explanation: If there are 4 stones in the heap, then you will never win the game; 14 | * No matter 1, 2, or 3 stones you remove, the last stone will always be 15 | * removed by your friend. 16 | */ 17 | pub struct Solution {} 18 | 19 | // problem: https://leetcode.com/problems/nim-game/ 20 | // discuss: https://leetcode.com/problems/nim-game/discuss/?currentPage=1&orderBy=most_votes&query= 21 | 22 | // submission codes start here 23 | 24 | impl Solution { 25 | pub fn can_win_nim(n: i32) -> bool { 26 | n % 4 != 0 27 | } 28 | } 29 | 30 | // submission codes end 31 | 32 | #[cfg(test)] 33 | mod tests { 34 | use super::*; 35 | 36 | #[test] 37 | fn test_292() { 38 | assert_eq!(Solution::can_win_nim(4), false); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/solution/s0300_longest_increasing_subsequence.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [300] Longest Increasing Subsequence 3 | * 4 | * Given an unsorted array of integers, find the length of longest increasing subsequence. 5 | * 6 | * Example: 7 | * 8 | * 9 | * Input: [10,9,2,5,3,7,101,18] 10 | * Output: 4 11 | * Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 12 | * 13 | * Note: 14 | * 15 | * 16 | * There may be more than one LIS combination, it is only necessary for you to return the length. 17 | * Your algorithm should run in O(n^2) complexity. 18 | * 19 | * 20 | * Follow up: Could you improve it to O(n log n) time complexity? 21 | * 22 | */ 23 | pub struct Solution {} 24 | 25 | // problem: https://leetcode.com/problems/longest-increasing-subsequence/ 26 | // discuss: https://leetcode.com/problems/longest-increasing-subsequence/discuss/?currentPage=1&orderBy=most_votes&query= 27 | 28 | // submission codes start here 29 | // N^2, DP: L[i] = max(1 + L[j]) for j in [0, i) and nums[j] < nums[i] 30 | // N * logN, kick out strategy, maintain an increasing array, new elements kick out a formal one larger than it, if the new element is largest, expand the array 31 | impl Solution { 32 | pub fn length_of_lis(nums: Vec) -> i32 { 33 | let mut incr = Vec::new(); 34 | for &num in nums.iter() { 35 | if let Err(idx) = incr.binary_search(&num) { 36 | if idx >= incr.len() { 37 | incr.push(num); 38 | } else { 39 | incr[idx] = num; 40 | } 41 | } 42 | } 43 | incr.len() as i32 44 | } 45 | } 46 | 47 | // submission codes end 48 | 49 | #[cfg(test)] 50 | mod tests { 51 | use super::*; 52 | 53 | #[test] 54 | fn test_300() { 55 | assert_eq!(Solution::length_of_lis(vec![10, 9, 2, 5, 3, 7, 101, 18]), 4); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/solution/s0303_range_sum_query_immutable.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [303] Range Sum Query - Immutable 3 | * 4 | * Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 5 | * 6 | * Example:
7 | * 8 | * Given nums = [-2, 0, 3, -5, 2, -1] 9 | * 10 | * sumRange(0, 2) -> 1 11 | * sumRange(2, 5) -> -1 12 | * sumRange(0, 5) -> -3 13 | * 14 | * 15 | * 16 | * Note:
17 | *
    18 | * You may assume that the array does not change. 19 | * There are many calls to sumRange function. 20 | *
21 | * 22 | */ 23 | pub struct Solution {} 24 | 25 | // problem: https://leetcode.com/problems/range-sum-query-immutable/ 26 | // discuss: https://leetcode.com/problems/range-sum-query-immutable/discuss/?currentPage=1&orderBy=most_votes&query= 27 | 28 | // submission codes start here 29 | 30 | struct NumArray { 31 | nums: Vec, 32 | } 33 | 34 | /** 35 | * `&self` means the method takes an immutable reference. 36 | * If you need a mutable reference, change it to `&mut self` instead. 37 | */ 38 | impl NumArray { 39 | fn new(nums: Vec) -> Self { 40 | let mut res = 0; 41 | let mut vec = Vec::with_capacity(nums.len()); 42 | for &num in nums.iter() { 43 | res += num; 44 | vec.push(res); 45 | } 46 | NumArray { nums: vec } 47 | } 48 | 49 | fn sum_range(&self, i: i32, j: i32) -> i32 { 50 | let (i, j) = (i as usize, j as usize); 51 | self.nums[j] - if i > 0 { self.nums[i - 1] } else { 0 } 52 | } 53 | } 54 | 55 | /** 56 | * Your NumArray object will be instantiated and called as such: 57 | * let obj = NumArray::new(nums); 58 | * let ret_1: i32 = obj.sum_range(i, j); 59 | */ 60 | 61 | // submission codes end 62 | 63 | #[cfg(test)] 64 | mod tests { 65 | use super::*; 66 | 67 | #[test] 68 | fn test_303() { 69 | let mut nums = NumArray::new(vec![-2, 0, 3, -5, 2, -1]); 70 | assert_eq!(nums.sum_range(0, 2), 1); 71 | assert_eq!(nums.sum_range(2, 5), -1); 72 | assert_eq!(nums.sum_range(0, 5), -3); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/solution/s0509_fibonacci_number.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [1013] Fibonacci Number 3 | * 4 | * The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 5 | * 6 | * 7 | * F(0) = 0, F(1) = 1 8 | * F(N) = F(N - 1) + F(N - 2), for N > 1. 9 | * 10 | * 11 | * Given N, calculate F(N). 12 | * 13 | * 14 | * 15 | * Example 1: 16 | * 17 | * 18 | * Input: 2 19 | * Output: 1 20 | * Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 21 | * 22 | * 23 | * Example 2: 24 | * 25 | * 26 | * Input: 3 27 | * Output: 2 28 | * Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 29 | * 30 | * 31 | * Example 3: 32 | * 33 | * 34 | * Input: 4 35 | * Output: 3 36 | * Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 37 | * 38 | * 39 | * 40 | * 41 | * Note: 42 | * 43 | * 0 ≤ N ≤ 30. 44 | * 45 | */ 46 | pub struct Solution {} 47 | 48 | // problem: https://leetcode.com/problems/fibonacci-number/ 49 | // discuss: https://leetcode.com/problems/fibonacci-number/discuss/?currentPage=1&orderBy=most_votes&query= 50 | 51 | // submission codes start here 52 | 53 | impl Solution { 54 | pub fn fib(n: i32) -> i32 { 55 | if n == 0 { 56 | return 0; 57 | } 58 | let mut f = (0, 1); 59 | for _ in 1..n { 60 | f = (f.1, f.0 + f.1); 61 | } 62 | return f.1; 63 | } 64 | } 65 | 66 | // submission codes end 67 | 68 | #[cfg(test)] 69 | mod tests { 70 | use super::*; 71 | 72 | #[test] 73 | fn test_1013() { 74 | assert_eq!(Solution::fib(2), 1); 75 | assert_eq!(Solution::fib(3), 2); 76 | assert_eq!(Solution::fib(4), 3); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/util/linked_list.rs: -------------------------------------------------------------------------------- 1 | #[derive(PartialEq, Eq, Debug)] 2 | pub struct ListNode { 3 | pub val: i32, 4 | pub next: Option>, 5 | } 6 | 7 | impl ListNode { 8 | #[inline] 9 | pub fn new(val: i32) -> Self { 10 | ListNode { next: None, val } 11 | } 12 | } 13 | 14 | // helper function for test 15 | pub fn to_list(vec: Vec) -> Option> { 16 | let mut current = None; 17 | for &v in vec.iter().rev() { 18 | let mut node = ListNode::new(v); 19 | node.next = current; 20 | current = Some(Box::new(node)); 21 | } 22 | current 23 | } 24 | 25 | #[macro_export] 26 | macro_rules! linked { 27 | ($($e:expr),*) => {to_list(vec![$($e.to_owned()), *])}; 28 | ($($e:expr,)*) => {to_list(vec![$($e.to_owned()), *])}; 29 | } 30 | -------------------------------------------------------------------------------- /src/util/mod.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | pub mod linked_list; 3 | #[macro_use] 4 | pub mod vec_string; 5 | #[macro_use] 6 | pub mod tree; 7 | #[macro_use] 8 | pub mod point; 9 | -------------------------------------------------------------------------------- /src/util/point.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug, PartialEq, Eq)] 2 | pub struct Point { 3 | pub x: i32, 4 | pub y: i32, 5 | } 6 | 7 | impl Point { 8 | #[inline] 9 | pub fn new(x: i32, y: i32) -> Self { 10 | Point { x, y } 11 | } 12 | } 13 | 14 | #[macro_export] 15 | macro_rules! point { 16 | ($($e:expr),*) => { 17 | { 18 | let vec = vec![$($e.to_owned()), *]; 19 | Point::new(vec[0], vec[1]) 20 | } 21 | }; 22 | ($($e:expr,)*) => (point![$($x),*]) 23 | } 24 | -------------------------------------------------------------------------------- /src/util/testing.rs: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/util/tree.rs: -------------------------------------------------------------------------------- 1 | use std::cell::RefCell; 2 | use std::rc::Rc; 3 | 4 | #[derive(Debug, PartialEq, Eq)] 5 | pub struct TreeNode { 6 | pub val: i32, 7 | pub left: Option>>, 8 | pub right: Option>>, 9 | } 10 | 11 | impl TreeNode { 12 | #[inline] 13 | pub fn new(val: i32) -> Self { 14 | TreeNode { 15 | val, 16 | left: None, 17 | right: None, 18 | } 19 | } 20 | } 21 | 22 | pub fn to_tree(vec: Vec>) -> Option>> { 23 | use std::collections::VecDeque; 24 | let head = Some(Rc::new(RefCell::new(TreeNode::new(vec[0].unwrap())))); 25 | let mut queue = VecDeque::new(); 26 | queue.push_back(head.as_ref().unwrap().clone()); 27 | 28 | for children in vec[1..].chunks(2) { 29 | let parent = queue.pop_front().unwrap(); 30 | if let Some(v) = children[0] { 31 | parent.borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 32 | queue.push_back(parent.borrow().left.as_ref().unwrap().clone()); 33 | } 34 | if children.len() > 1 { 35 | if let Some(v) = children[1] { 36 | parent.borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(v)))); 37 | queue.push_back(parent.borrow().right.as_ref().unwrap().clone()); 38 | } 39 | } 40 | } 41 | head 42 | } 43 | 44 | #[macro_export] 45 | macro_rules! tree { 46 | () => { 47 | None 48 | }; 49 | ($($e:expr),*) => { 50 | { 51 | let vec = vec![$(stringify!($e)), *]; 52 | let vec = vec.into_iter().map(|v| v.parse::().ok()).collect::>(); 53 | to_tree(vec) 54 | } 55 | }; 56 | ($($e:expr,)*) => {(tree![$($e),*])}; 57 | } 58 | -------------------------------------------------------------------------------- /src/util/vec_string.rs: -------------------------------------------------------------------------------- 1 | #[macro_export] 2 | macro_rules! vec_string { 3 | ($($e:expr),*) => {vec![$($e.to_owned()), *]}; 4 | ($($e:expr,)*) => {vec![$($e.to_owned()), *]}; 5 | } 6 | -------------------------------------------------------------------------------- /template.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [__PROBLEM_ID__] __PROBLEM_TITLE__ 3 | * 4 | * __PROBLEM_DESC__ 5 | */ 6 | pub struct Solution {}__EXTRA_USE__ 7 | 8 | // problem: __PROBLEM_LINK__ 9 | // discuss: __DISCUSS_LINK__ 10 | 11 | // submission codes start here 12 | 13 | __PROBLEM_DEFAULT_CODE__ 14 | 15 | // submission codes end 16 | 17 | #[cfg(test)] 18 | mod tests { 19 | use super::*; 20 | 21 | #[test] 22 | fn test___PROBLEM_ID__() { 23 | } 24 | } 25 | --------------------------------------------------------------------------------