diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 261eeb9e..00000000 --- a/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/README.md b/README.md index 587b18a2..e69de29b 100644 --- a/README.md +++ b/README.md @@ -1,18 +0,0 @@ -# My Leetcode Solution in Rust - -Run `cargo run {id}` to initialize the template submission file of "question #id". - -Run `cargo test test_{id}` to test the solution for "question #id". - -对于大部分难度为 Hard 的问题, 会有中文的思路注释 - -Working in progress, to do: - -- [ ] auto generation of solution list (when 100 problems solved) - -## Usage - -* Remove all the solution .rs -* Clean lib.rs file -* Start your leetcode journey in rust by typing `cargo run {question_id}` - diff --git a/src/solution/s0001_two_sum.rs b/src/solution/s0001_two_sum.rs deleted file mode 100644 index 4a44a732..00000000 --- a/src/solution/s0001_two_sum.rs +++ /dev/null @@ -1,53 +0,0 @@ -/** - * [1] Two Sum - * - * Given an array of integers, return indices of the two numbers such that they - * add up to a specific target. - * - * You may assume that each input would have exactly one solution, and you may - * not use the same element twice. - * - * Example: - * - * - * Given nums = [2, 7, 11, 15], target = 9, - * - * Because nums[0] + nums[1] = 2 + 7 = 9, - * return [0, 1]. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/two-sum/ -// discuss: https://leetcode.com/problems/two-sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::HashMap; -impl Solution { - pub fn two_sum(nums: Vec, target: i32) -> Vec { - let mut map = HashMap::with_capacity(nums.len()); - for (index, num) in nums.iter().enumerate() { - match map.get(&(target - num)) { - None => { - map.insert(num, index); - } - Some(sub_index) => return vec![*sub_index as i32, index as i32], - } - } - vec![] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_1() { - assert_eq!(vec![0, 1], Solution::two_sum(vec![2, 7, 11, 15], 9)); - assert_eq!(vec![1, 2], Solution::two_sum(vec![3, 2, 4], 6)); - } -} diff --git a/src/solution/s0002_add_two_numbers.rs b/src/solution/s0002_add_two_numbers.rs deleted file mode 100644 index d8bfc2d8..00000000 --- a/src/solution/s0002_add_two_numbers.rs +++ /dev/null @@ -1,98 +0,0 @@ -/** - * [2] Add Two Numbers - * - * You are given two non-empty linked lists representing two non-negative - * integers. The digits are stored in reverse order and each of their nodes - * contain a single digit. Add the two numbers and return it as a linked list. - * - * You may assume the two numbers do not contain any leading zero, except the - * number 0 itself. - * - * Example: - * - * - * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) - * Output: 7 -> 0 -> 8 - * Explanation: 342 + 465 = 807. - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/add-two-numbers/ -// discuss: https://leetcode.com/problems/add-two-numbers/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn add_two_numbers( - l1: Option>, - l2: Option>, - ) -> Option> { - let (mut l1, mut l2) = (l1, l2); - let mut dummy_head = Some(Box::new(ListNode::new(0))); - let mut tail = &mut dummy_head; - let (mut l1_end, mut l2_end, mut overflow) = (false, false, false); - loop { - let lhs = match l1 { - Some(node) => { - l1 = node.next; - node.val - } - None => { - l1_end = true; - 0 - } - }; - let rhs = match l2 { - Some(node) => { - l2 = node.next; - node.val - } - None => { - l2_end = true; - 0 - } - }; - // if l1, l2 end and there is not overflow from previous operation, return the result - if l1_end && l2_end && !overflow { - break dummy_head.unwrap().next; - } - let sum = lhs + rhs + if overflow { 1 } else { 0 }; - let sum = if sum >= 10 { - overflow = true; - sum - 10 - } else { - overflow = false; - sum - }; - tail.as_mut().unwrap().next = Some(Box::new(ListNode::new(sum))); - tail = &mut tail.as_mut().unwrap().next - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_2() { - assert_eq!( - Solution::add_two_numbers(to_list(vec![2, 4, 3]), to_list(vec![5, 6, 4])), - to_list(vec![7, 0, 8]) - ); - - assert_eq!( - Solution::add_two_numbers(to_list(vec![9, 9, 9, 9]), to_list(vec![9, 9, 9, 9, 9, 9])), - to_list(vec![8, 9, 9, 9, 0, 0, 1]) - ); - - assert_eq!( - Solution::add_two_numbers(to_list(vec![0]), to_list(vec![0])), - to_list(vec![0]) - ) - } -} diff --git a/src/solution/s0003_longest_substring_without_repeating_characters.rs b/src/solution/s0003_longest_substring_without_repeating_characters.rs deleted file mode 100644 index 0ad6903d..00000000 --- a/src/solution/s0003_longest_substring_without_repeating_characters.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [3] Longest Substring Without Repeating Characters - * - * Given a string, find the length of the longest substring without repeating characters. - * - * Example: - * - * Input: "abcabcbb" - * Output: 3 - * Explanation: The answer is "abc", with the length of 3. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/longest-substring-without-repeating-characters/ -// discuss: https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn length_of_longest_substring(s: String) -> i32 { - let seq: Vec = s.chars().collect(); - let len = seq.len(); - let (mut start, mut end, mut max) = (0, 0, 0); - - while end < len { - for idx in start..end { - if seq[end] == seq[idx] { - start = idx + 1; - break; - } - } - let curr = end - start + 1; - if curr > max { - max = curr - } - end += 1 - } - max as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_3() { - assert_eq!( - Solution::length_of_longest_substring("abcabcbb".to_string()), - 3 - ); - assert_eq!(Solution::length_of_longest_substring("bbbb".to_string()), 1); - assert_eq!( - Solution::length_of_longest_substring("pwwkew".to_string()), - 3 - ); - } -} diff --git a/src/solution/s0004_median_of_two_sorted_arrays.rs b/src/solution/s0004_median_of_two_sorted_arrays.rs deleted file mode 100644 index e3c2d014..00000000 --- a/src/solution/s0004_median_of_two_sorted_arrays.rs +++ /dev/null @@ -1,62 +0,0 @@ -/** - * [4] Median of Two Sorted Arrays - * - * There are two sorted arrays nums1 and nums2 of size m and n respectively. - * - * Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). - * - * You may assume nums1 and nums2 cannot be both empty. - * - * Example 1: - * - * - * nums1 = [1, 3] - * nums2 = [2] - * - * The median is 2.0 - * - * - * Example 2: - * - * - * nums1 = [1, 2] - * nums2 = [3, 4] - * - * The median is (2 + 3)/2 = 2.5 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/median-of-two-sorted-arrays/ -// discuss: https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO: nth slice -impl Solution { - pub fn find_median_sorted_arrays(nums1: Vec, nums2: Vec) -> f64 { - 1.0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - // TODO: implementation - #[test] - #[ignore] - fn test_4() { - assert_eq!( - Solution::find_median_sorted_arrays(vec![1, 3], vec![2]), - 2.0 - ); - assert_eq!( - Solution::find_median_sorted_arrays(vec![1, 2], vec![3, 4]), - 2.5 - ); - } -} diff --git a/src/solution/s0005_longest_palindromic_substring.rs b/src/solution/s0005_longest_palindromic_substring.rs deleted file mode 100644 index 675e1951..00000000 --- a/src/solution/s0005_longest_palindromic_substring.rs +++ /dev/null @@ -1,82 +0,0 @@ -/** - * [5] Longest Palindromic Substring - * - * Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. - * - * Example 1: - * - * - * Input: "babad" - * Output: "bab" - * Note: "aba" is also a valid answer. - * - * - * Example 2: - * - * - * Input: "cbbd" - * Output: "bb" - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/longest-palindromic-substring/ -// discuss: https://leetcode.com/problems/longest-palindromic-substring/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn longest_palindrome(s: String) -> String { - let seq: Vec = s.chars().collect(); - let len = seq.len(); - if len < 1 { - return s; - } - let (mut idx, mut curr_len, mut curr_start, mut curr_end) = (0, 0, 0, 0); - while idx < len { - let (mut i, mut j) = (idx, idx); - let ch = seq[idx]; - // handle same char - while i > 0 && seq[i - 1] == ch { - i -= 1 - } - while j < len - 1 && seq[j + 1] == ch { - j += 1 - } - idx = j + 1; - while i > 0 && j < len - 1 && seq[i - 1] == seq[j + 1] { - i -= 1; - j += 1; - } - let max_len = j - i + 1; - if max_len > curr_len { - curr_len = max_len; - curr_start = i; - curr_end = j; - } - if max_len >= len - 1 { - break; - } - } - - s[curr_start..curr_end + 1].to_owned() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_5() { - assert_eq!(Solution::longest_palindrome("aaaaa".to_owned()), "aaaaa"); - assert_eq!(Solution::longest_palindrome("babab".to_owned()), "babab"); - assert_eq!(Solution::longest_palindrome("babcd".to_owned()), "bab"); - assert_eq!(Solution::longest_palindrome("cbbd".to_owned()), "bb"); - assert_eq!(Solution::longest_palindrome("bb".to_owned()), "bb"); - assert_eq!(Solution::longest_palindrome("".to_owned()), ""); - } -} diff --git a/src/solution/s0006_zigzag_conversion.rs b/src/solution/s0006_zigzag_conversion.rs deleted file mode 100644 index 51ed13a7..00000000 --- a/src/solution/s0006_zigzag_conversion.rs +++ /dev/null @@ -1,95 +0,0 @@ -/** - * [6] ZigZag Conversion - * - * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) - * - * - * P A H N - * A P L S I I G - * Y I R - * - * - * And then read line by line: "PAHNAPLSIIGYIR" - * - * Write the code that will take a string and make this conversion given a number of rows: - * - * - * string convert(string s, int numRows); - * - * Example 1: - * - * - * Input: s = "PAYPALISHIRING", numRows = 3 - * Output: "PAHNAPLSIIGYIR" - * - * - * Example 2: - * - * - * Input: s = "PAYPALISHIRING", numRows = 4 - * Output: "PINALSIGYAHRPI" - * Explanation: - * - * P I N - * A L S I G - * Y A H R - * P I - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/zigzag-conversion/ -// discuss: https://leetcode.com/problems/zigzag-conversion/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn convert(s: String, num_rows: i32) -> String { - if num_rows < 2 { - return s; - } - let seq: Vec = s.chars().collect(); - let len = seq.len(); - let unit: usize = (2 * num_rows - 2) as usize; - let mut sb = String::with_capacity(s.capacity()); - for row in 0..num_rows { - let mut i = row as usize; - let step1 = 2 * (num_rows - 1 - row) as usize; - let step2 = (unit - step1) as usize; - let mut trigger = false; - while i < len { - sb.push(seq[i]); - if step1 == 0 { - i += step2 - } else if step2 == 0 { - i += step1 - } else { - i += if trigger { step2 } else { step1 }; - trigger = !trigger; - } - } - } - sb - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_6() { - assert_eq!( - Solution::convert("PAYPALISHIRING".to_string(), 4), - "PINALSIGYAHRPI" - ); - assert_eq!( - Solution::convert("PAYPALISHIRING".to_string(), 3), - "PAHNAPLSIIGYIR" - ); - assert_eq!(Solution::convert("A".to_string(), 1), "A"); - assert_eq!(Solution::convert("AY".to_string(), 2), "AY"); - } -} diff --git a/src/solution/s0007_reverse_integer.rs b/src/solution/s0007_reverse_integer.rs deleted file mode 100644 index ad89eebd..00000000 --- a/src/solution/s0007_reverse_integer.rs +++ /dev/null @@ -1,73 +0,0 @@ -/** - * [7] Reverse Integer - * - * Given a 32-bit signed integer, reverse digits of an integer. - * - * Example 1: - * - * - * Input: 123 - * Output: 321 - * - * - * Example 2: - * - * - * Input: -123 - * Output: -321 - * - * - * Example 3: - * - * - * Input: 120 - * Output: 21 - * - * - * Note:
- * 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. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/reverse-integer/ -// discuss: https://leetcode.com/problems/reverse-integer/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -impl Solution { - pub fn reverse(x: i32) -> i32 { - let mut input: i64 = x as i64; - let mut result: i64 = 0; - let mut digit: i64 = 0; - let base: i64 = 2; - let upper_bound: i64 = base.pow(31) - 1; - let lower_bound: i64 = -base.pow(31); - while input != 0 { - digit = input % 10; - result = result * 10 + digit; - input = input / 10; - } - if result > upper_bound || result < lower_bound { - return 0; - } - result as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_7() { - assert_eq!(Solution::reverse(123), 321); - assert_eq!(Solution::reverse(-123), -321); - assert_eq!(Solution::reverse(0), 0); - assert_eq!(Solution::reverse(-123000), -321); - let base: i64 = 2; - assert_eq!(Solution::reverse((base.pow(31) - 1) as i32), 0); - assert_eq!(Solution::reverse((-base.pow(31)) as i32), 0); - } -} diff --git a/src/solution/s0008_string_to_integer_atoi.rs b/src/solution/s0008_string_to_integer_atoi.rs deleted file mode 100644 index 9c86e17b..00000000 --- a/src/solution/s0008_string_to_integer_atoi.rs +++ /dev/null @@ -1,131 +0,0 @@ -/** - * [8] String to Integer (atoi) - * - * Implement atoi which converts a string to an integer. - * - * The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. - * - * The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. - * - * If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. - * - * If no valid conversion could be performed, a zero value is returned. - * - * Note: - * - *
    - *
  • Only the space character ' ' is considered as whitespace character.
  • - *
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31, 2^31 - 1]. If the numerical value is out of the range of representable values, INT_MAX (2^31 - 1) or INT_MIN (-2^31) is returned.
  • - *
- * - * Example 1: - * - * - * Input: "42" - * Output: 42 - * - * - * Example 2: - * - * - * Input: " -42" - * Output: -42 - * Explanation: The first non-whitespace character is '-', which is the minus sign. - * Then take as many numerical digits as possible, which gets 42. - * - * - * Example 3: - * - * - * Input: "4193 with words" - * Output: 4193 - * Explanation: Conversion stops at digit '3' as the next character is not a numerical digit. - * - * - * Example 4: - * - * - * Input: "words and 987" - * Output: 0 - * Explanation: The first non-whitespace character is 'w', which is not a numerical - * digit or a +/- sign. Therefore no valid conversion could be performed. - * - * Example 5: - * - * - * Input: "-91283472332" - * Output: -2147483648 - * Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. - * Thefore INT_MIN (-2^31) is returned. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/string-to-integer-atoi/ -// discuss: https://leetcode.com/problems/string-to-integer-atoi/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn my_atoi(input: String) -> i32 { - let (i32_min, i32_max) = (-2_i64.pow(31), 2_i64.pow(31) - 1); - let mut result: i64 = 0; - let mut minus = false; - // simple state machine - let mut num_matched = false; - for ch in input.chars().into_iter() { - if !num_matched { - match ch { - ' ' => {} - '0'..='9' => { - num_matched = true; - result = result * 10 + ch.to_digit(10).unwrap() as i64; - } - '-' => { - num_matched = true; - minus = true; - } - '+' => { - num_matched = true; - } - _ => return 0, - } - } else { - match ch { - '0'..='9' => { - result = result * 10 + ch.to_digit(10).unwrap() as i64; - if result > i32_max { - break; - } - } - _ => break, - } - } - } - result = if minus { -result } else { result }; - if result > i32_max { - return i32_max as i32; - } - if result < i32_min { - return i32_min as i32; - } - return result as i32; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_8() { - assert_eq!(Solution::my_atoi("aa".to_string()), 0); - assert_eq!(Solution::my_atoi("-91283472332".to_string()), -2147483648); - assert_eq!(Solution::my_atoi("words and 987".to_string()), 0); - assert_eq!(Solution::my_atoi("4193 with words".to_string()), 4193); - assert_eq!(Solution::my_atoi("42".to_string()), 42); - assert_eq!(Solution::my_atoi("004193333".to_string()), 4193333); - } -} diff --git a/src/solution/s0009_palindrome_number.rs b/src/solution/s0009_palindrome_number.rs deleted file mode 100644 index 255eeed1..00000000 --- a/src/solution/s0009_palindrome_number.rs +++ /dev/null @@ -1,89 +0,0 @@ -/** - * [9] Palindrome Number - * - * Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. - * - * Example 1: - * - * - * Input: 121 - * Output: true - * - * - * Example 2: - * - * - * Input: -121 - * Output: false - * Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. - * - * - * Example 3: - * - * - * Input: 10 - * Output: false - * Explanation: Reads 01 from right to left. Therefore it is not a palindrome. - * - * - * Follow up: - * - * Coud you solve it without converting the integer to a string? - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/palindrome-number/ -// discuss: https://leetcode.com/problems/palindrome-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO: not optimal, we only have to revert half of the string -impl Solution { - pub fn is_palindrome(x: i32) -> bool { - if x < 0 { - return false; - } - let mut digits: Vec = Vec::new(); - let mut input = x; - while input != 0 { - digits.push(input % 10); - input = input / 10; - } - let len = digits.len(); - // handle one digit - if len < 2 { - return true; - } - // handle end with 0 - if digits[0] == 0 { - return false; - } - let mut i = 0; - while i < len / 2 { - if digits[i] != digits[len - 1 - i] { - return false; - } - i += 1; - } - true - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_9() { - assert_eq!(Solution::is_palindrome(-32), false); - assert_eq!(Solution::is_palindrome(10), false); - assert_eq!(Solution::is_palindrome(0), true); - assert_eq!(Solution::is_palindrome(9), true); - assert_eq!(Solution::is_palindrome(121), true); - assert_eq!(Solution::is_palindrome(2222), true); - assert_eq!(Solution::is_palindrome(11222211), true); - } -} diff --git a/src/solution/s0010_regular_expression_matching.rs b/src/solution/s0010_regular_expression_matching.rs deleted file mode 100644 index 13e15cb7..00000000 --- a/src/solution/s0010_regular_expression_matching.rs +++ /dev/null @@ -1,92 +0,0 @@ -/** - * [10] Regular Expression Matching - * - * Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. - * - * - * '.' Matches any single character. - * '*' Matches zero or more of the preceding element. - * - * - * The matching should cover the entire input string (not partial). - * - * Note: - * - * - * s could be empty and contains only lowercase letters a-z. - * p could be empty and contains only lowercase letters a-z, and characters like . or *. - * - * - * Example 1: - * - * - * Input: - * s = "aa" - * p = "a" - * Output: false - * Explanation: "a" does not match the entire string "aa". - * - * - * Example 2: - * - * - * Input: - * s = "aa" - * p = "a*" - * Output: true - * Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". - * - * - * Example 3: - * - * - * Input: - * s = "ab" - * p = ".*" - * Output: true - * Explanation: ".*" means "zero or more (*) of any character (.)". - * - * - * Example 4: - * - * - * Input: - * s = "aab" - * p = "c*a*b" - * Output: true - * Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab". - * - * - * Example 5: - * - * - * Input: - * s = "mississippi" - * p = "mis*is*p*." - * Output: false - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/regular-expression-matching/ -// discuss: https://leetcode.com/problems/regular-expression-matching/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO: NFA -impl Solution { - pub fn is_match(s: String, p: String) -> bool { - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_10() {} -} diff --git a/src/solution/s0011_container_with_most_water.rs b/src/solution/s0011_container_with_most_water.rs deleted file mode 100644 index ae818bac..00000000 --- a/src/solution/s0011_container_with_most_water.rs +++ /dev/null @@ -1,81 +0,0 @@ -/** - * [11] Container With Most Water - * - * Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. - * - * Note: You may not slant the container and n is at least 2. - * - * - * - * - * - * The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. - * - * - * - * Example: - * - * - * Input: [1,8,6,2,5,4,8,3,7] - * Output: 49 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/container-with-most-water/ -// discuss: https://leetcode.com/problems/container-with-most-water/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Brute force: O(N^2) - -// Two Pointer: a[0] -> <- a[n-1] -impl Solution { - pub fn max_area(height: Vec) -> i32 { - let (mut start, mut end) = (0_usize, (height.len() - 1)); - let mut max: i32 = (end - start) as i32 * Solution::min(height[start], height[end]); - let mut curr_area: i32 = 0; - while end - start > 1 { - // move the lower one - if height[start] < height[end] { - start += 1; - if height[start] < height[start - 1] { - continue; - } - } else { - end -= 1; - if height[end] < height[end + 1] { - continue; - } - } - curr_area = (end - start) as i32 * Solution::min(height[start], height[end]); - if curr_area > max { - max = curr_area - } - } - max - } - - #[inline(always)] - fn min(i: i32, j: i32) -> i32 { - if i > j { - j - } else { - i - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_11() { - assert_eq!(Solution::max_area(vec![1, 8, 6, 2, 5, 4, 8, 3, 7]), 49); - assert_eq!(Solution::max_area(vec![6, 9]), 6); - assert_eq!(Solution::max_area(vec![1, 1, 2, 1, 1, 1]), 5); - } -} diff --git a/src/solution/s0012_integer_to_roman.rs b/src/solution/s0012_integer_to_roman.rs deleted file mode 100644 index b32592c7..00000000 --- a/src/solution/s0012_integer_to_roman.rs +++ /dev/null @@ -1,114 +0,0 @@ -/** - * [12] Integer to Roman - * - * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. - * - * - * Symbol Value - * I 1 - * V 5 - * X 10 - * L 50 - * C 100 - * D 500 - * M 1000 - * - * For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. - * - * Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: - * - * - * I can be placed before V (5) and X (10) to make 4 and 9. - * X can be placed before L (50) and C (100) to make 40 and 90. - * C can be placed before D (500) and M (1000) to make 400 and 900. - * - * - * Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. - * - * Example 1: - * - * - * Input: 3 - * Output: "III" - * - * Example 2: - * - * - * Input: 4 - * Output: "IV" - * - * Example 3: - * - * - * Input: 9 - * Output: "IX" - * - * Example 4: - * - * - * Input: 58 - * Output: "LVIII" - * Explanation: L = 50, V = 5, III = 3. - * - * - * Example 5: - * - * - * Input: 1994 - * Output: "MCMXCIV" - * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/integer-to-roman/ -// discuss: https://leetcode.com/problems/integer-to-roman/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn int_to_roman(num: i32) -> String { - let table: Vec<(i32, &'static str)> = vec![ - (1000, "M"), - (900, "CM"), - (500, "D"), - (400, "CD"), - (100, "C"), - (90, "XC"), - (50, "L"), - (40, "XL"), - (10, "X"), - (9, "IX"), - (5, "V"), - (4, "IV"), - (1, "I"), - ]; - - let mut num = num; - let mut sb = String::new(); - for p in table.iter() { - if num >= p.0 { - for _ in 0..(num / p.0) { - sb.push_str(p.1); - } - num = num % p.0 - } - } - sb - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_12() { - assert_eq!(Solution::int_to_roman(3), "III"); - assert_eq!(Solution::int_to_roman(4), "IV"); - assert_eq!(Solution::int_to_roman(9), "IX"); - assert_eq!(Solution::int_to_roman(1994), "MCMXCIV"); - } -} diff --git a/src/solution/s0013_roman_to_integer.rs b/src/solution/s0013_roman_to_integer.rs deleted file mode 100644 index 4f3f0ae4..00000000 --- a/src/solution/s0013_roman_to_integer.rs +++ /dev/null @@ -1,115 +0,0 @@ -/** - * [13] Roman to Integer - * - * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. - * - * - * Symbol Value - * I 1 - * V 5 - * X 10 - * L 50 - * C 100 - * D 500 - * M 1000 - * - * For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. - * - * Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: - * - * - * I can be placed before V (5) and X (10) to make 4 and 9. - * X can be placed before L (50) and C (100) to make 40 and 90. - * C can be placed before D (500) and M (1000) to make 400 and 900. - * - * - * Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. - * - * Example 1: - * - * - * Input: "III" - * Output: 3 - * - * Example 2: - * - * - * Input: "IV" - * Output: 4 - * - * Example 3: - * - * - * Input: "IX" - * Output: 9 - * - * Example 4: - * - * - * Input: "LVIII" - * Output: 58 - * Explanation: L = 50, V= 5, III = 3. - * - * - * Example 5: - * - * - * Input: "MCMXCIV" - * Output: 1994 - * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/roman-to-integer/ -// discuss: https://leetcode.com/problems/roman-to-integer/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn roman_to_int(s: String) -> i32 { - let table: Vec<(i32, &'static str)> = vec![ - (1000, "M"), - (900, "CM"), - (500, "D"), - (400, "CD"), - (100, "C"), - (90, "XC"), - (50, "L"), - (40, "XL"), - (10, "X"), - (9, "IX"), - (5, "V"), - (4, "IV"), - (1, "I"), - ]; - let mut sum = 0; - let mut idx = 0; - for p in table.iter() { - while idx + p.1.len() <= s.len() && p.1 == &s[idx..idx + p.1.len()] { - idx += p.1.len(); - sum += p.0; - if idx >= s.len() { - return sum; - } - } - } - sum - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_13() { - assert_eq!(Solution::roman_to_int("III".to_string()), 3); - assert_eq!(Solution::roman_to_int("IV".to_string()), 4); - assert_eq!(Solution::roman_to_int("IX".to_string()), 9); - assert_eq!(Solution::roman_to_int("MCMXCIV".to_string()), 1994); - assert_eq!(Solution::roman_to_int("DCXXI".to_string()), 621); - } -} diff --git a/src/solution/s0014_longest_common_prefix.rs b/src/solution/s0014_longest_common_prefix.rs deleted file mode 100644 index 1c5fd985..00000000 --- a/src/solution/s0014_longest_common_prefix.rs +++ /dev/null @@ -1,90 +0,0 @@ -/** - * [14] Longest Common Prefix - * - * Write a function to find the longest common prefix string amongst an array of strings. - * - * If there is no common prefix, return an empty string "". - * - * Example 1: - * - * - * Input: ["flower","flow","flight"] - * Output: "fl" - * - * - * Example 2: - * - * - * Input: ["dog","racecar","car"] - * Output: "" - * Explanation: There is no common prefix among the input strings. - * - * - * Note: - * - * All given inputs are in lowercase letters a-z. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/longest-common-prefix/ -// discuss: https://leetcode.com/problems/longest-common-prefix/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::str::Chars; -impl Solution { - pub fn longest_common_prefix(strs: Vec) -> String { - let mut prefix = String::new(); - let mut iters: Vec = strs.iter().map(|s| s.chars()).collect(); - let mut curr_char: Option = None; - if strs.len() < 1 { - return prefix; - } - loop { - curr_char.take().map(|ch| prefix.push(ch)); - for iter in iters.iter_mut() { - let mut ch = iter.next(); - if ch.is_none() { - return prefix; - } - match curr_char { - None => curr_char = ch.take(), - Some(curr) => { - if curr != ch.unwrap() { - return prefix; - } - } - } - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_14() { - assert_eq!( - Solution::longest_common_prefix(vec![ - "".to_string(), - "racecar".to_string(), - "car".to_string() - ]), - "" - ); - assert_eq!( - Solution::longest_common_prefix(vec![ - "flower".to_string(), - "flow".to_string(), - "flight".to_string() - ]), - "fl" - ); - assert_eq!(Solution::longest_common_prefix(vec![]), ""); - } -} diff --git a/src/solution/s0015_3sum.rs b/src/solution/s0015_3sum.rs deleted file mode 100644 index 9feb3cd0..00000000 --- a/src/solution/s0015_3sum.rs +++ /dev/null @@ -1,143 +0,0 @@ -/** - * [15] 3Sum - * - * Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. - * - * Note: - * - * The solution set must not contain duplicate triplets. - * - * Example: - * - * - * Given array nums = [-1, 0, 1, 2, -1, -4], - * - * A solution set is: - * [ - * [-1, 0, 1], - * [-1, -1, 2] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/3sum/ -// discuss: https://leetcode.com/problems/3sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn three_sum(nums: Vec) -> Vec> { - let len = nums.len(); - if len < 3 { - return vec![]; - } - let mut nums = nums; - nums.sort(); - let mut i = 0; - let mut result: Vec> = Vec::new(); - let mut previous = nums[0] - 1; - while i < len - 2 { - // skip same number - if nums[i] == previous { - i += 1; - continue; - } - previous = nums[i]; - let mut vec = Solution::two_sum(&nums[(i + 1)..len], 0 - nums[i]); - for t in vec.iter() { - result.push(vec![nums[i], t.0, t.1]); - } - i += 1; - } - result - } - - // 2 sum using 2 pointers: nums[0] -> <- nums[len-1] - #[inline(always)] - fn two_sum(nums: &[i32], sum: i32) -> Vec<(i32, i32)> { - let (mut i, mut j) = (0_usize, nums.len() - 1); - let mut result = Vec::new(); - while i < j { - if nums[i] + nums[j] < sum { - i += 1 - } else if nums[i] + nums[j] > sum { - j -= 1 - } else { - result.push((nums[i], nums[j])); - i = Solution::next_unique(nums, i, true); - j = Solution::next_unique(nums, j, false); - } - } - result - } - - // seek next un-repeat number - #[inline(always)] - fn next_unique(nums: &[i32], idx: usize, forward: bool) -> usize { - let curr = nums[idx]; - let mut i = idx; - while i > 0 && i < nums.len() && nums[i] == curr { - i = if forward { i + 1 } else { i - 1 } - } - i - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_15() { - assert_eq!( - Solution::three_sum(vec![-1, 0, 1, 2, -1, -4]), - vec![vec![-1, -1, 2], vec![-1, 0, 1]] - ); - assert_eq!( - Solution::three_sum(vec![ - -7, -4, -6, 6, 4, -6, -9, -10, -7, 5, 3, -1, -5, 8, -1, -2, -8, -1, 5, -3, -5, 4, - 2, -5, -4, 4, 7 - ]), - vec![ - vec![-10, 2, 8], - vec![-10, 3, 7], - vec![-10, 4, 6], - vec![-10, 5, 5], - vec![-9, 2, 7], - vec![-9, 3, 6], - vec![-9, 4, 5], - vec![-8, 2, 6], - vec![-8, 3, 5], - vec![-8, 4, 4], - vec![-7, -1, 8], - vec![-7, 2, 5], - vec![-7, 3, 4], - vec![-6, -2, 8], - vec![-6, -1, 7], - vec![-6, 2, 4], - vec![-5, -3, 8], - vec![-5, -2, 7], - vec![-5, -1, 6], - vec![-5, 2, 3], - vec![-4, -4, 8], - vec![-4, -3, 7], - vec![-4, -2, 6], - vec![-4, -1, 5], - vec![-3, -2, 5], - vec![-3, -1, 4], - vec![-2, -1, 3], - vec![-1, -1, 2] - ] - ); - assert_eq!( - Solution::three_sum(vec![2, 0, -2, -5, -5, -3, 2, -4]), - vec![vec![-4, 2, 2], vec![-2, 0, 2]] - ); - let empty_vec: Vec> = vec![]; - assert_eq!(Solution::three_sum(vec![]), empty_vec); - } -} diff --git a/src/solution/s0016_3sum_closest.rs b/src/solution/s0016_3sum_closest.rs deleted file mode 100644 index 01cf442d..00000000 --- a/src/solution/s0016_3sum_closest.rs +++ /dev/null @@ -1,76 +0,0 @@ -/** - * [16] 3Sum Closest - * - * Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. - * - * Example: - * - * - * Given array nums = [-1, 2, 1, -4], and target = 1. - * - * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/3sum-closest/ -// discuss: https://leetcode.com/problems/3sum-closest/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn three_sum_closest(nums: Vec, target: i32) -> i32 { - let mut nums = nums; - let mut min_distance: i32 = i32::max_value(); - nums.sort(); - let mut i = 0; - while i < nums.len() - 2 { - let sub_min = Solution::two_sum_closest(&nums[(i + 1)..nums.len()], target - nums[i]); - if sub_min.abs() < min_distance.abs() { - min_distance = sub_min; - if min_distance == 0 { - break; - } - } - i += 1; - } - target + min_distance - } - - pub fn two_sum_closest(nums: &[i32], target: i32) -> i32 { - let (mut i, mut j) = (0_usize, nums.len() - 1); - let mut local_min = i32::max_value(); - while i < j { - let sum = nums[i] + nums[j]; - if sum > target { - j -= 1; - } else if sum < target { - i += 1; - } else { - return 0; - } - if (sum - target).abs() < local_min.abs() { - local_min = sum - target - } - } - local_min - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_16() { - assert_eq!(Solution::three_sum_closest(vec![-1, 2, 1, -4], 1), 2); - assert_eq!(Solution::three_sum_closest(vec![1, 2, 3], 1), 6); - assert_eq!( - Solution::three_sum_closest(vec![1, 2, 4, 8, 16, 32, 64, 128], 82), - 82 - ); - } -} diff --git a/src/solution/s0017_letter_combinations_of_a_phone_number.rs b/src/solution/s0017_letter_combinations_of_a_phone_number.rs deleted file mode 100644 index 7d3245f4..00000000 --- a/src/solution/s0017_letter_combinations_of_a_phone_number.rs +++ /dev/null @@ -1,81 +0,0 @@ -/** - * [17] Letter Combinations of a Phone Number - * - * Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. - * - * A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. - * - * - * - * Example: - * - * - * Input: "23" - * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. - * - * - * Note: - * - * Although the above answer is in lexicographical order, your answer could be in any order you want. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/letter-combinations-of-a-phone-number/ -// discuss: https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn letter_combinations(digits: String) -> Vec { - // '0' and '1' as placeholder to avoid index shifting - let table: Vec<(char, Vec)> = vec![ - ('0', vec![]), - ('1', vec![]), - ('2', vec!['a', 'b', 'c']), - ('3', vec!['d', 'e', 'f']), - ('4', vec!['g', 'h', 'i']), - ('5', vec!['j', 'k', 'l']), - ('6', vec!['m', 'n', 'o']), - ('7', vec!['p', 'q', 'r', 's']), - ('8', vec!['t', 'u', 'v']), - ('9', vec!['w', 'x', 'y', 'z']), - ]; - if digits.len() < 1 { - return vec![]; - } - let mut combs: Vec = vec![String::with_capacity(digits.len())]; - for ch in digits.chars().into_iter() { - let chs = &table[ch.to_digit(10).unwrap() as usize].1; - let mut added: Vec = Vec::with_capacity((chs.len() - 1) * combs.len()); - for comb in combs.iter_mut() { - for (i, &alphabetic) in chs.iter().enumerate() { - if i == chs.len() - 1 { - comb.push(alphabetic); - } else { - let mut new_comb = (*comb).clone(); - new_comb.push(alphabetic); - added.push(new_comb); - } - } - } - combs.append(&mut added); - } - combs - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_17() { - assert_eq!( - Solution::letter_combinations("23".to_string()), - ["cf", "af", "bf", "cd", "ce", "ad", "ae", "bd", "be"] - ); - } -} diff --git a/src/solution/s0018_4sum.rs b/src/solution/s0018_4sum.rs deleted file mode 100644 index d832aef1..00000000 --- a/src/solution/s0018_4sum.rs +++ /dev/null @@ -1,99 +0,0 @@ -/** - * [18] 4Sum - * - * Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. - * - * Note: - * - * The solution set must not contain duplicate quadruplets. - * - * Example: - * - * - * Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. - * - * A solution set is: - * [ - * [-1, 0, 0, 1], - * [-2, -1, 1, 2], - * [-2, 0, 0, 2] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/4sum/ -// discuss: https://leetcode.com/problems/4sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO: change to faster N^3 solution... maybe -// this is a N^2 * logN solution, but slower than N^3 solution -// iterate all combinations and the sum of 2 elements, then use one-round hash -use std::collections::BTreeMap; -use std::collections::HashSet; -impl Solution { - pub fn four_sum(nums: Vec, target: i32) -> Vec> { - if nums.len() < 4 { - return vec![]; - } - let mut set: HashSet> = HashSet::new(); - let mut map: BTreeMap> = BTreeMap::new(); - // collect two-sums in asc order, store the index to avoid single number reusing - for i in 0..(nums.len() - 1) { - for j in (i + 1)..nums.len() { - map.entry(nums[i] + nums[j]) - .or_insert(Vec::new()) - .push((i, j)); - } - } - // find results - for (&sum, pairs) in map.iter() { - // avoid duplicates - if sum > target / 2 { - break; - } - match map.get(&(target - sum)) { - None => continue, - // 2-sum + 2-sum == target, then all the possible combination - // (without index conflicts) is our answer - Some(subs) => { - for pair in pairs.iter() { - for sub in subs.iter() { - if sub.0 == pair.0 - || sub.0 == pair.1 - || sub.1 == pair.0 - || sub.1 == pair.1 - { - continue; - } - let mut vec = - vec![nums[pair.0], nums[pair.1], nums[sub.0], nums[sub.1]]; - vec.sort(); - set.insert(vec); - } - } - } - } - } - set.into_iter().collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - // TODO: build a macro for arbitrary match - #[test] - #[ignore] - fn test_18() { - assert_eq!( - Solution::four_sum(vec![1, 0, -1, 0, -2, 2], 0), - vec![vec![-1, 0, 0, 1], vec![-2, 0, 0, 2], vec![-2, -1, 1, 2]] - ); - } -} diff --git a/src/solution/s0019_remove_nth_node_from_end_of_list.rs b/src/solution/s0019_remove_nth_node_from_end_of_list.rs deleted file mode 100644 index c3f53a32..00000000 --- a/src/solution/s0019_remove_nth_node_from_end_of_list.rs +++ /dev/null @@ -1,71 +0,0 @@ -/** - * [19] Remove Nth Node From End of List - * - * Given a linked list, remove the n-th node from the end of list and return its head. - * - * Example: - * - * - * Given linked list: 1->2->3->4->5, and n = 2. - * - * After removing the second node from the end, the linked list becomes 1->2->3->5. - * - * - * Note: - * - * Given n will always be valid. - * - * Follow up: - * - * Could you do this in one pass? - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/remove-nth-node-from-end-of-list/ -// discuss: https://leetcode.com/problems/remove-nth-node-from-end-of-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// one pass (two pointer runner pattern) cannot make borrow checker happy -// but two pass don't takes longer time -impl Solution { - pub fn remove_nth_from_end(head: Option>, n: i32) -> Option> { - let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head })); - let mut len = 0; - { - let mut p = dummy_head.as_ref(); - while p.unwrap().next.is_some() { - len += 1; - p = p.unwrap().next.as_ref(); - } - } - let idx = len - n; - { - let mut p = dummy_head.as_mut(); - for _ in 0..(idx) { - p = p.unwrap().next.as_mut(); - } - let next = p.as_mut().unwrap().next.as_mut().unwrap().next.take(); - p.as_mut().unwrap().next = next; - } - dummy_head.unwrap().next - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_19() { - assert_eq!( - Solution::remove_nth_from_end(to_list(vec![1, 2, 3, 4, 5]), 2), - to_list(vec![1, 2, 3, 5]) - ); - assert_eq!(Solution::remove_nth_from_end(to_list(vec![1]), 1), None); - } -} diff --git a/src/solution/s0020_valid_parentheses.rs b/src/solution/s0020_valid_parentheses.rs deleted file mode 100644 index 3c0940b9..00000000 --- a/src/solution/s0020_valid_parentheses.rs +++ /dev/null @@ -1,94 +0,0 @@ -/** - * [20] Valid Parentheses - * - * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. - * - * An input string is valid if: - * - *
    - * Open brackets must be closed by the same type of brackets. - * Open brackets must be closed in the correct order. - *
- * - * Note that an empty string is also considered valid. - * - * Example 1: - * - * - * Input: "()" - * Output: true - * - * - * Example 2: - * - * - * Input: "()[]{}" - * Output: true - * - * - * Example 3: - * - * - * Input: "(]" - * Output: false - * - * - * Example 4: - * - * - * Input: "([)]" - * Output: false - * - * - * Example 5: - * - * - * Input: "{[]}" - * Output: true - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/valid-parentheses/ -// discuss: https://leetcode.com/problems/valid-parentheses/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn is_valid(s: String) -> bool { - let mut stack: Vec = Vec::new(); - for ch in s.chars().into_iter() { - match stack.last() { - None => {} - Some(&last) => { - if Solution::pair(last, ch) { - stack.pop(); - continue; - } - } - } - stack.push(ch); - } - stack.is_empty() - } - - #[inline(always)] - fn pair(open: char, close: char) -> bool { - (open == '{' && close == '}') - || (open == '(' && close == ')') - || (open == '[' && close == ']') - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_20() { - assert_eq!(Solution::is_valid("()[]{}".to_string()), true); - } -} diff --git a/src/solution/s0021_merge_two_sorted_lists.rs b/src/solution/s0021_merge_two_sorted_lists.rs deleted file mode 100644 index 54d7f256..00000000 --- a/src/solution/s0021_merge_two_sorted_lists.rs +++ /dev/null @@ -1,75 +0,0 @@ -/** - * [21] Merge Two Sorted Lists - * - * Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. - * - * Example: - * - * Input: 1->2->4, 1->3->4 - * Output: 1->1->2->3->4->4 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/merge-two-sorted-lists/ -// discuss: https://leetcode.com/problems/merge-two-sorted-lists/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// recursive will be much easier to understand -impl Solution { - pub fn merge_two_lists( - l1: Option>, - l2: Option>, - ) -> Option> { - let mut dummy_head = Some(Box::new(ListNode { val: 0, next: None })); - let mut head = &mut dummy_head; - let (mut l1, mut l2) = (l1, l2); - while l1.is_some() || l2.is_some() { - if l1.is_none() { - head.as_mut().unwrap().next = l2; - break; - } else if l2.is_none() { - head.as_mut().unwrap().next = l1; - break; - } - let next = if l1.as_ref().unwrap().val < l2.as_ref().unwrap().val { - let (origin, next) = Solution::take_head(l1); - l1 = origin; - next - } else { - let (origin, next) = Solution::take_head(l2); - l2 = origin; - next - }; - head.as_mut().unwrap().next = next; - head = &mut head.as_mut().unwrap().next; - } - dummy_head.unwrap().next - } - - #[inline(always)] - fn take_head(mut l: Option>) -> (Option>, Option>) { - let l_next = l.as_mut().unwrap().next.take(); - let next = l.take(); - l = l_next; - (l, next) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_21() { - assert_eq!( - Solution::merge_two_lists(to_list(vec![1, 2, 4]), to_list(vec![1, 3, 4])), - to_list(vec![1, 1, 2, 3, 4, 4]) - ); - } -} diff --git a/src/solution/s0022_generate_parentheses.rs b/src/solution/s0022_generate_parentheses.rs deleted file mode 100644 index 9e0e33df..00000000 --- a/src/solution/s0022_generate_parentheses.rs +++ /dev/null @@ -1,72 +0,0 @@ -/** - * [22] Generate Parentheses - * - * - * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. - * - * - * - * For example, given n = 3, a solution set is: - * - * - * [ - * "((()))", - * "(()())", - * "(())()", - * "()(())", - * "()()()" - * ] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/generate-parentheses/ -// discuss: https://leetcode.com/problems/generate-parentheses/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// DFS -impl Solution { - pub fn generate_parenthesis(n: i32) -> Vec { - if n < 1 { - return vec![]; - } - let mut result = Vec::new(); - Solution::dfs(n, 0, 0, &mut result, String::new()); - result - } - - fn dfs(n: i32, left: i32, right: i32, result: &mut Vec, mut path: String) { - if left == n && right == n { - result.push(path); - return; - } - if left < n { - let mut new_path = path.clone(); - new_path.push('('); - Solution::dfs(n, left + 1, right, result, new_path); - } - if right < left { - // reuse path to avoid clone overhead - path.push(')'); - Solution::dfs(n, left, right + 1, result, path); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_22() { - assert_eq!(Solution::generate_parenthesis(1), vec!["()"]); - assert_eq!(Solution::generate_parenthesis(2), vec!["(())", "()()"]); - assert_eq!( - Solution::generate_parenthesis(3), - vec!["((()))", "(()())", "(())()", "()(())", "()()()"] - ); - } -} diff --git a/src/solution/s0023_merge_k_sorted_lists.rs b/src/solution/s0023_merge_k_sorted_lists.rs deleted file mode 100644 index eeaf3695..00000000 --- a/src/solution/s0023_merge_k_sorted_lists.rs +++ /dev/null @@ -1,95 +0,0 @@ -/** - * [23] Merge k Sorted Lists - * - * Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. - * - * Example: - * - * - * Input: - * [ - * 1->4->5, - * 1->3->4, - * 2->6 - * ] - * Output: 1->1->2->3->4->4->5->6 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/merge-k-sorted-lists/ -// discuss: https://leetcode.com/problems/merge-k-sorted-lists/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -use std::cmp::Ordering; -use std::collections::BinaryHeap; - -// head value and the index -struct Node(i32, usize); - -// sort in reverse order of head value -impl Ord for Node { - fn cmp(&self, other: &Self) -> Ordering { - self.0.cmp(&other.0).reverse() - } -} -impl PartialEq for Node { - fn eq(&self, other: &Self) -> bool { - self.0.eq(&other.0) - } -} -impl Eq for Node {} -impl PartialOrd for Node { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.0.cmp(&other.0).reverse()) - } -} - -impl Solution { - pub fn merge_k_lists(lists: Vec>>) -> Option> { - let mut heap: BinaryHeap = BinaryHeap::new(); - for (idx, node) in lists.iter().enumerate() { - node.as_ref() - .and_then(|n| Some(heap.push(Node(n.val, idx)))); - } - Solution::next(lists, &mut heap) - } - - fn next( - mut lists: Vec>>, - heap: &mut BinaryHeap, - ) -> Option> { - heap.pop().map(|node| { - let next = lists[node.1].take().unwrap().next; - next.as_ref() - .and_then(|n| Some(heap.push(Node(n.val, node.1)))); - lists[node.1] = next; - Box::new(ListNode { - val: node.0, - next: Solution::next(lists, heap), - }) - }) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_23() { - assert_eq!( - Solution::merge_k_lists(vec![ - to_list(vec![1, 4, 5]), - to_list(vec![1, 3, 4]), - to_list(vec![2, 6]), - ]), - to_list(vec![1, 1, 2, 3, 4, 4, 5, 6]) - ); - assert_eq!(Solution::merge_k_lists(vec![]), None); - } -} diff --git a/src/solution/s0024_swap_nodes_in_pairs.rs b/src/solution/s0024_swap_nodes_in_pairs.rs deleted file mode 100644 index 4a6deb3e..00000000 --- a/src/solution/s0024_swap_nodes_in_pairs.rs +++ /dev/null @@ -1,73 +0,0 @@ -/** - * [24] Swap Nodes in Pairs - * - * Given a linked list, swap every two adjacent nodes and return its head. - * - * Example: - * - * - * Given 1->2->3->4, you should return the list as 2->1->4->3. - * - * Note: - * - * - * Your algorithm should use only constant extra space. - * You may not modify the values in the list's nodes, only nodes itself may be changed. - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/swap-nodes-in-pairs/ -// discuss: https://leetcode.com/problems/swap-nodes-in-pairs/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn swap_pairs(head: Option>) -> Option> { - let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head })); - let mut head = dummy_head.as_mut(); - loop { - let mut left = head.as_mut().unwrap().next.take(); - if left.is_none() { - break; - } - let mut right = left.as_mut().unwrap().next.take(); - // handle the un-paired one, e.g. [1, 2, 3] -> [2, 1, 3], 3 is un-paired - if right.is_none() { - head.as_mut().unwrap().next = left; - break; - } - let mut next = right.as_mut().unwrap().next.take(); - // BEFORE: head -> left -> right -> next - // AFTER: head -> right -> left -> next - left.as_mut().unwrap().next = next; - right.as_mut().unwrap().next = left; - head.as_mut().unwrap().next = right; - head = head.unwrap().next.as_mut().unwrap().next.as_mut(); - } - dummy_head.unwrap().next - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_24() { - assert_eq!( - Solution::swap_pairs(to_list(vec![1, 2, 3, 4])), - to_list(vec![2, 1, 4, 3]) - ); - assert_eq!(Solution::swap_pairs(to_list(vec![])), to_list(vec![])); - assert_eq!( - Solution::swap_pairs(to_list(vec![1, 2, 3])), - to_list(vec![2, 1, 3]) - ); - assert_eq!(Solution::swap_pairs(to_list(vec![1])), to_list(vec![1])); - } -} diff --git a/src/solution/s0025_reverse_nodes_in_k_group.rs b/src/solution/s0025_reverse_nodes_in_k_group.rs deleted file mode 100644 index 5d39cd1e..00000000 --- a/src/solution/s0025_reverse_nodes_in_k_group.rs +++ /dev/null @@ -1,106 +0,0 @@ -/** - * [25] Reverse Nodes in k-Group - * - * Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. - * - * k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. - * - * - * - * - * Example: - * - * Given this linked list: 1->2->3->4->5 - * - * For k = 2, you should return: 2->1->4->3->5 - * - * For k = 3, you should return: 3->2->1->4->5 - * - * Note: - * - * - * Only constant extra memory is allowed. - * You may not alter the values in the list's nodes, only nodes itself may be changed. - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/reverse-nodes-in-k-group/ -// discuss: https://leetcode.com/problems/reverse-nodes-in-k-group/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn reverse_k_group(head: Option>, k: i32) -> Option> { - let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head })); - let mut head = dummy_head.as_mut(); - 'outer: loop { - let mut start = head.as_mut().unwrap().next.take(); - if start.is_none() { - break 'outer; - } - let mut end = start.as_mut(); - for _ in 0..(k - 1) { - end = end.unwrap().next.as_mut(); - if end.is_none() { - head.as_mut().unwrap().next = start; - break 'outer; - } - } - let mut tail = end.as_mut().unwrap().next.take(); - // BEFORE: head -> start -> 123456... -> end -> tail - // AFTER: head -> end -> ...654321 -> start -> tail - let end = Solution::reverse(start, tail); - head.as_mut().unwrap().next = end; - for _ in 0..k { - head = head.unwrap().next.as_mut() - } - } - dummy_head.unwrap().next - } - - #[inline(always)] - fn reverse( - mut head: Option>, - tail: Option>, - ) -> Option> { - let mut prev = tail; - let mut current = head; - while let Some(mut current_node_inner) = current { - let mut next = current_node_inner.next.take(); - current_node_inner.next = prev.take(); - prev = Some(current_node_inner); - current = next; - } - prev - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_25() { - assert_eq!( - Solution::reverse_k_group(to_list(vec![1, 2, 3, 4, 5]), 2), - to_list(vec![2, 1, 4, 3, 5]) - ); - assert_eq!( - Solution::reverse_k_group(to_list(vec![1, 2, 3, 4, 5]), 3), - to_list(vec![3, 2, 1, 4, 5]) - ); - assert_eq!( - Solution::reverse_k_group(to_list(vec![1, 2, 3, 4, 5]), 5), - to_list(vec![5, 4, 3, 2, 1]) - ); - assert_eq!( - Solution::reverse_k_group(to_list(vec![1]), 1), - to_list(vec![1]) - ); - } -} diff --git a/src/solution/s0026_remove_duplicates_from_sorted_array.rs b/src/solution/s0026_remove_duplicates_from_sorted_array.rs deleted file mode 100644 index 286b7c54..00000000 --- a/src/solution/s0026_remove_duplicates_from_sorted_array.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [26] Remove Duplicates from Sorted Array - * - * Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. - * - * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. - * - * Example 1: - * - * - * Given nums = [1,1,2], - * - * Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. - * - * It doesn't matter what you leave beyond the returned length. - * - * Example 2: - * - * - * Given nums = [0,0,1,1,1,2,2,3,3,4], - * - * Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. - * - * It doesn't matter what values are set beyond the returned length. - * - * - * Clarification: - * - * Confused why the returned value is an integer but your answer is an array? - * - * Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. - * - * Internally you can think of this: - * - * - * // nums is passed in by reference. (i.e., without making a copy) - * int len = removeDuplicates(nums); - * - * // any modification to nums in your function would be known by the caller. - * // using the length returned by your function, it prints the first len elements. - * for (int i = 0; i < len; i++) { - * print(nums[i]); - * } - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/remove-duplicates-from-sorted-array/ -// discuss: https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn remove_duplicates(nums: &mut Vec) -> i32 { - let len = nums.len(); - if len <= 1 { - return len as i32; - } - let mut slow = 0usize; - for fast in 1..len { - if nums[slow] != nums[fast] { - slow += 1; - nums[slow] = nums[fast]; - } - } - nums.truncate(slow + 1); - (slow + 1) as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_26() { - assert_eq!(Solution::remove_duplicates(&mut vec![]), 0); - let mut vec1 = vec![1, 1, 1, 1, 3]; - assert_eq!(Solution::remove_duplicates(&mut vec1), 2); - assert_eq!(vec1, vec![1, 3]); - let mut vec2 = vec![1, 1, 2]; - assert_eq!(Solution::remove_duplicates(&mut vec2), 2); - assert_eq!(vec2, vec![1, 2]); - } -} diff --git a/src/solution/s0027_remove_element.rs b/src/solution/s0027_remove_element.rs deleted file mode 100644 index 7144d3e9..00000000 --- a/src/solution/s0027_remove_element.rs +++ /dev/null @@ -1,97 +0,0 @@ -/** - * [27] Remove Element - * - * Given an array nums and a value val, remove all instances of that value in-place and return the new length. - * - * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. - * - * The order of elements can be changed. It doesn't matter what you leave beyond the new length. - * - * Example 1: - * - * - * Given nums = [3,2,2,3], val = 3, - * - * Your function should return length = 2, with the first two elements of nums being 2. - * - * It doesn't matter what you leave beyond the returned length. - * - * - * Example 2: - * - * - * Given nums = [0,1,2,2,3,0,4,2], val = 2, - * - * Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. - * - * Note that the order of those five elements can be arbitrary. - * - * It doesn't matter what values are set beyond the returned length. - * - * Clarification: - * - * Confused why the returned value is an integer but your answer is an array? - * - * Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. - * - * Internally you can think of this: - * - * - * // nums is passed in by reference. (i.e., without making a copy) - * int len = removeElement(nums, val); - * - * // any modification to nums in your function would be known by the caller. - * // using the length returned by your function, it prints the first len elements. - * for (int i = 0; i < len; i++) { - * print(nums[i]); - * } - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/remove-element/ -// discuss: https://leetcode.com/problems/remove-element/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn remove_element(nums: &mut Vec, val: i32) -> i32 { - if nums.len() < 1 { - return 0; - } - let (mut start, mut end) = (0_usize, nums.len() - 1); - while start < end { - if nums[start] == val { - nums[start] = nums[end - 1]; - end -= 1; - } else { - start += 1; - } - } - end as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_27() { - let mut vec1 = vec![0, 1, 2, 2, 3, 0, 4, 2]; - assert_eq!(Solution::remove_element(&mut vec1, 2), 5); - assert_eq!(vec1[0..5], [0, 1, 4, 0, 3]); - assert_eq!(Solution::remove_element(&mut vec![], 2), 0); - assert_eq!( - Solution::remove_element(&mut vec![1, 2, 2, 2, 2, 2, 2], 2), - 1 - ); - assert_eq!( - Solution::remove_element(&mut vec![2, 2, 2, 2, 2, 2, 2], 2), - 0 - ); - assert_eq!(Solution::remove_element(&mut vec![1], 1), 0); - } -} diff --git a/src/solution/s0028_implement_strstr.rs b/src/solution/s0028_implement_strstr.rs deleted file mode 100644 index e0d944ee..00000000 --- a/src/solution/s0028_implement_strstr.rs +++ /dev/null @@ -1,55 +0,0 @@ -/** - * [28] Implement strStr() - * - * Implement strStr(). - * - * Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. - * - * Example 1: - * - * - * Input: haystack = "hello", needle = "ll" - * Output: 2 - * - * - * Example 2: - * - * - * Input: haystack = "aaaaa", needle = "bba" - * Output: -1 - * - * - * Clarification: - * - * What should we return when needle is an empty string? This is a great question to ask during an interview. - * - * 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(). - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/implement-strstr/ -// discuss: https://leetcode.com/problems/implement-strstr/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn str_str(haystack: String, needle: String) -> i32 { - if needle.is_empty() { - return 0; - } - haystack.find(&needle).map_or(-1_i32, |v| v as i32) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_28() { - assert_eq!(Solution::str_str("hello".to_string(), "ll".to_string()), 2) - } -} diff --git a/src/solution/s0029_divide_two_integers.rs b/src/solution/s0029_divide_two_integers.rs deleted file mode 100644 index e8f13435..00000000 --- a/src/solution/s0029_divide_two_integers.rs +++ /dev/null @@ -1,52 +0,0 @@ -/** - * [29] Divide Two Integers - * - * Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. - * - * Return the quotient after dividing dividend by divisor. - * - * The integer division should truncate toward zero. - * - * Example 1: - * - * - * Input: dividend = 10, divisor = 3 - * Output: 3 - * - * Example 2: - * - * - * Input: dividend = 7, divisor = -3 - * Output: -2 - * - * Note: - * - * - * Both dividend and divisor will be 32-bit signed integers. - * The divisor will never be 0. - * 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. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/divide-two-integers/ -// discuss: https://leetcode.com/problems/divide-two-integers/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn divide(dividend: i32, divisor: i32) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_29() {} -} diff --git a/src/solution/s0030_substring_with_concatenation_of_all_words.rs b/src/solution/s0030_substring_with_concatenation_of_all_words.rs deleted file mode 100644 index 002ae9a3..00000000 --- a/src/solution/s0030_substring_with_concatenation_of_all_words.rs +++ /dev/null @@ -1,175 +0,0 @@ -/** - * [30] Substring with Concatenation of All Words - * - * You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters. - * - * Example 1: - * - * - * Input: - * s = "barfoothefoobarman", - * words = ["foo","bar"] - * Output: [0,9] - * Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively. - * The output order does not matter, returning [9,0] is fine too. - * - * - * Example 2: - * - * - * Input: - * s = "wordgoodgoodgoodbestword", - * words = ["word","good","best","word"] - * Output: [] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/substring-with-concatenation-of-all-words/ -// discuss: https://leetcode.com/problems/substring-with-concatenation-of-all-words/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -struct Term { - expect: i32, - count: i32, -} -impl Term { - fn new(expect: i32, count: i32) -> Self { - Term { expect, count } - } - fn inc_expect(&mut self) { - self.expect += 1; - } - fn inc(&mut self) { - self.count += 1; - } - fn dec(&mut self) { - self.count -= 1; - } - fn exhausted(&self) -> bool { - self.count > self.expect - } - fn reset(&mut self) { - self.count = 0; - } -} - -use std::collections::hash_map::Entry; -use std::collections::HashMap; - -impl Solution { - pub fn find_substring(s: String, words: Vec) -> Vec { - if words.len() < 1 { - return vec![]; - } - let word_len = words[0].len(); - if word_len < 1 { - return vec![]; - } - let substr_len = word_len * words.len(); - let mut map: HashMap<&str, Term> = HashMap::with_capacity(words.len()); - for word in words.iter() { - map.entry(word).or_insert(Term::new(0, 0)).inc_expect(); - } - let mut result: Vec = Vec::new(); - // we can split terms in N ways, where N = word_len - for shift in 0..word_len { - let mut i = shift; - let mut j = shift; - // we do a sliding window for each round - while j + word_len - 1 < s.len() { - match map.entry(&s[j..j + word_len]) { - Entry::Occupied(mut entry) => { - entry.get_mut().inc(); - // term exhausted, shrink the window to release - if entry.get().exhausted() { - while i < j { - let term = &s[i..i + word_len]; - map.entry(term).and_modify(|t| t.dec()); - i += word_len; - if term == &s[j..j + word_len] { - break; - } - } - j += word_len; - } else { - if j - i < (words.len() - 1) * word_len { - j += word_len; - } else { - // matched! - result.push(i as i32); - // move the whole window, release the dropped term - map.entry(&s[i..i + word_len]).and_modify(|t| t.dec()); - j += word_len; - i += word_len; - } - } - } - // bad term, move over and do a reset - Entry::Vacant(entry) => { - map.iter_mut().for_each(|(_, v)| v.reset()); - j += word_len; - i = j; - } - } - } - map.iter_mut().for_each(|(_, v)| v.reset()) - } - result - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_30() { - assert_eq!( - Solution::find_substring( - "barfoothefoobarman".to_string(), - vec!["foo".to_string(), "bar".to_string()] - ), - vec![0, 9] - ); - assert_eq!( - Solution::find_substring( - "wordgoodgoodgoodbestword".to_string(), - vec![ - "word".to_string(), - "good".to_string(), - "best".to_string(), - "word".to_string() - ] - ), - vec![] - ); - assert_eq!( - Solution::find_substring( - "wordgoodgoodgoodbestword".to_string(), - vec![ - "word".to_string(), - "good".to_string(), - "best".to_string(), - "good".to_string() - ] - ), - vec![8] - ); - assert_eq!( - Solution::find_substring( - "xxwordgoodgoodgoodbestword".to_string(), - vec![ - "word".to_string(), - "good".to_string(), - "best".to_string(), - "good".to_string() - ] - ), - vec![10] - ); - } -} diff --git a/src/solution/s0031_next_permutation.rs b/src/solution/s0031_next_permutation.rs deleted file mode 100644 index b448dfa1..00000000 --- a/src/solution/s0031_next_permutation.rs +++ /dev/null @@ -1,89 +0,0 @@ -/** - * [31] Next Permutation - * - * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. - * - * If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). - * - * The replacement must be in-place and use only constant extra memory. - * - * Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. - * - * 1,2,3 → 1,3,2
- * 3,2,1 → 1,2,3
- * 1,1,5 → 1,5,1 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/next-permutation/ -// discuss: https://leetcode.com/problems/next-permutation/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn next_permutation(nums: &mut Vec) { - let len = nums.len(); - let mut i = (len - 1) as i32; - let mut prev = -1; - // find the decrement digit from end - while i >= 0 { - if nums[i as usize] < prev { - break; - } - prev = nums[i as usize]; - i -= 1; - } - let mut j = len - 1; - // find the first digit larger than nums[i] - // we can do binary search here to make a slightly improvement - if i >= 0 { - while j > (i as usize) { - if nums[j] > nums[i as usize] { - nums.swap(i as usize, j); - break; - } - j -= 1; - } - } - let slice = &mut nums[((i + 1) as usize)..len]; - slice.reverse(); - } -} - -// submission codes end - -/* -// a clean solution (from leetcode submissions) -impl Solution { - pub fn next_permutation(a: &mut Vec) { - let n = a.len(); - - if let Some(i) = (1..n).rev().find(|&i| a[i - 1] < a[i]) { - let j = (i..n).rev().find(|&j| a[i - 1] < a[j]) - .unwrap(); - - a.swap(i - 1, j); - a[i..].reverse(); - } else { - a.reverse(); - } - } -} - */ - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_31() { - let mut vec1 = vec![1, 2, 3, 4, 5]; - Solution::next_permutation(&mut vec1); - assert_eq!(vec1, vec![1, 2, 3, 5, 4]); - - let mut vec2 = vec![5, 4, 3, 2, 1]; - Solution::next_permutation(&mut vec2); - assert_eq!(vec2, vec![1, 2, 3, 4, 5]); - } -} diff --git a/src/solution/s0032_longest_valid_parentheses.rs b/src/solution/s0032_longest_valid_parentheses.rs deleted file mode 100644 index d970de2b..00000000 --- a/src/solution/s0032_longest_valid_parentheses.rs +++ /dev/null @@ -1,95 +0,0 @@ -/** - * [32] Longest Valid Parentheses - * - * Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. - * - * Example 1: - * - * - * Input: "(()" - * Output: 2 - * Explanation: The longest valid parentheses substring is "()" - * - * - * Example 2: - * - * - * Input: ")()())" - * Output: 4 - * Explanation: The longest valid parentheses substring is "()()" - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/longest-valid-parentheses/ -// discuss: https://leetcode.com/problems/longest-valid-parentheses/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// time: O(N) space: O(1) -impl Solution { - pub fn longest_valid_parentheses(s: String) -> i32 { - let mut seq: Vec = s.chars().collect(); - let forward_max = Solution::longest(&seq, '('); - seq.reverse(); - let backward_max = Solution::longest(&seq, ')'); - i32::max(forward_max, backward_max) - } - - fn longest(seq: &Vec, plus_char: char) -> i32 { - let mut stack = 0; - let mut max_len = 0; - let (mut i, mut j) = (0_usize, 0_usize); - while j < seq.len() { - if seq[j] == plus_char { - stack += 1; - } else { - // stack exhausted, shift over - if stack < 1 { - i = j + 1; - } else { - stack -= 1; - if stack == 0 { - max_len = i32::max(max_len, (j - i + 1) as i32); - } - } - } - j += 1; - } - max_len - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_32() { - assert_eq!(Solution::longest_valid_parentheses(")()())".to_string()), 4); - assert_eq!(Solution::longest_valid_parentheses(")(".to_string()), 0); - assert_eq!(Solution::longest_valid_parentheses("(()".to_string()), 2); - assert_eq!( - Solution::longest_valid_parentheses("(((((()()".to_string()), - 4 - ); - assert_eq!( - Solution::longest_valid_parentheses("((((((((()))".to_string()), - 6 - ); - assert_eq!(Solution::longest_valid_parentheses("()".to_string()), 2); - assert_eq!(Solution::longest_valid_parentheses("()(()".to_string()), 2); - assert_eq!( - Solution::longest_valid_parentheses(")()(((())))(".to_string()), - 10 - ); - assert_eq!( - Solution::longest_valid_parentheses("(()(((()".to_string()), - 2 - ); - assert_eq!(Solution::longest_valid_parentheses("".to_string()), 0); - } -} diff --git a/src/solution/s0033_search_in_rotated_sorted_array.rs b/src/solution/s0033_search_in_rotated_sorted_array.rs deleted file mode 100644 index ab5c13d3..00000000 --- a/src/solution/s0033_search_in_rotated_sorted_array.rs +++ /dev/null @@ -1,105 +0,0 @@ -/** - * [33] Search in Rotated Sorted Array - * - * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. - * - * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). - * - * You are given a target value to search. If found in the array return its index, otherwise return -1. - * - * You may assume no duplicate exists in the array. - * - * Your algorithm's runtime complexity must be in the order of O(log n). - * - * Example 1: - * - * - * Input: nums = [4,5,6,7,0,1,2], target = 0 - * Output: 4 - * - * - * Example 2: - * - * - * Input: nums = [4,5,6,7,0,1,2], target = 3 - * Output: -1 - * - */ -pub struct Solution {} - -/* - \ - 8 - 7 9 - 6 1 - 5 2 - 3 \ -Consider the given array as ring, each time we split the ring and judge which part is the target belong to, then it's ordinary binary search. -*/ - -// problem: https://leetcode.com/problems/search-in-rotated-sorted-array/ -// discuss: https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn search(nums: Vec, target: i32) -> i32 { - let mut size = nums.len(); - if size == 0 { - return -1; - } - let mut base = 0_usize; - while size > 1 { - let half = size / 2; - let mid = base + half; - if nums[mid] == target { - return mid as i32; - } - // we split the ring to [base..half] & [half+1..base-1] - // if target not in [base..half] ring, move base to select another ring - if !(((nums[base] < nums[mid]) && (target >= nums[base] && target <= nums[mid])) - || ((nums[base] > nums[mid]) && (target >= nums[base] || target <= nums[mid]))) - { - base = mid; - } - size -= half; - } - if nums[base] == target { - base as i32 - } else { - -1 - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_33() { - assert_eq!(Solution::search(vec![7, 8, 1, 2, 3, 4, 5, 6], 2), 3); - assert_eq!( - Solution::search( - vec![ - 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 0, 1, 2, 3, 4, 5, 6, 7, 8 - ], - 0 - ), - 9 - ); - assert_eq!( - Solution::search( - vec![ - 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 0, 1, 2, 3, 4, 5, 6, 7, 8 - ], - 1006 - ), - 2 - ); - assert_eq!(Solution::search(vec![4, 5, 6, 7, 0, 1, 2], 3), -1); - assert_eq!(Solution::search(vec![], 3), -1); - } -} diff --git a/src/solution/s0034_find_first_and_last_position_of_element_in_sorted_array.rs b/src/solution/s0034_find_first_and_last_position_of_element_in_sorted_array.rs deleted file mode 100644 index eba1c01c..00000000 --- a/src/solution/s0034_find_first_and_last_position_of_element_in_sorted_array.rs +++ /dev/null @@ -1,45 +0,0 @@ -/** - * [34] Find First and Last Position of Element in Sorted Array - * - * Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. - * - * Your algorithm's runtime complexity must be in the order of O(log n). - * - * If the target is not found in the array, return [-1, -1]. - * - * Example 1: - * - * - * Input: nums = [5,7,7,8,8,10], target = 8 - * Output: [3,4] - * - * Example 2: - * - * - * Input: nums = [5,7,7,8,8,10], target = 6 - * Output: [-1,-1] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ -// discuss: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO -impl Solution { - pub fn search_range(nums: Vec, target: i32) -> Vec { - vec![] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_34() {} -} diff --git a/src/solution/s0035_search_insert_position.rs b/src/solution/s0035_search_insert_position.rs deleted file mode 100644 index 31c1c38b..00000000 --- a/src/solution/s0035_search_insert_position.rs +++ /dev/null @@ -1,59 +0,0 @@ -/** - * [35] Search Insert Position - * - * 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. - * - * You may assume no duplicates in the array. - * - * Example 1: - * - * - * Input: [1,3,5,6], 5 - * Output: 2 - * - * - * Example 2: - * - * - * Input: [1,3,5,6], 2 - * Output: 1 - * - * - * Example 3: - * - * - * Input: [1,3,5,6], 7 - * Output: 4 - * - * - * Example 4: - * - * - * Input: [1,3,5,6], 0 - * Output: 0 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/search-insert-position/ -// discuss: https://leetcode.com/problems/search-insert-position/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO -impl Solution { - pub fn search_insert(nums: Vec, target: i32) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_35() {} -} diff --git a/src/solution/s0036_valid_sudoku.rs b/src/solution/s0036_valid_sudoku.rs deleted file mode 100644 index 5a595774..00000000 --- a/src/solution/s0036_valid_sudoku.rs +++ /dev/null @@ -1,172 +0,0 @@ -/** - * [36] Valid Sudoku - * - * Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: - * - *
    - * Each row must contain the digits 1-9 without repetition. - * Each column must contain the digits 1-9 without repetition. - * Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition. - *
- * - *
- * A partially filled sudoku which is valid. - * - * The Sudoku board could be partially filled, where empty cells are filled with the character '.'. - * - * Example 1: - * - * - * Input: - * [ - * ["5","3",".",".","7",".",".",".","."], - * ["6",".",".","1","9","5",".",".","."], - * [".","9","8",".",".",".",".","6","."], - * ["8",".",".",".","6",".",".",".","3"], - * ["4",".",".","8",".","3",".",".","1"], - * ["7",".",".",".","2",".",".",".","6"], - * [".","6",".",".",".",".","2","8","."], - * [".",".",".","4","1","9",".",".","5"], - * [".",".",".",".","8",".",".","7","9"] - * ] - * Output: true - * - * - * Example 2: - * - * - * Input: - * [ - * ["8","3",".",".","7",".",".",".","."], - * ["6",".",".","1","9","5",".",".","."], - * [".","9","8",".",".",".",".","6","."], - * ["8",".",".",".","6",".",".",".","3"], - * ["4",".",".","8",".","3",".",".","1"], - * ["7",".",".",".","2",".",".",".","6"], - * [".","6",".",".",".",".","2","8","."], - * [".",".",".","4","1","9",".",".","5"], - * [".",".",".",".","8",".",".","7","9"] - * ] - * Output: false - * Explanation: Same as Example 1, except with the 5 in the top left corner being - * modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid. - * - * - * Note: - * - * - * A Sudoku board (partially filled) could be valid but is not necessarily solvable. - * Only the filled cells need to be validated according to the mentioned rules. - * The given board contain only digits 1-9 and the character '.'. - * The given board size is always 9x9. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/valid-sudoku/ -// discuss: https://leetcode.com/problems/valid-sudoku/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// just brute force -impl Solution { - pub fn is_valid_sudoku(board: Vec>) -> bool { - let mut table = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - for row in board.iter() { - for z in 1..10 { - table[z] = 0; - } - for ch in row { - match ch.to_digit(10) { - None => continue, - Some(idx) => { - if table[idx as usize] > 0 { - return false; - } else { - table[idx as usize] = 1 - } - } - } - } - } - for i in 0..9 { - for z in 1..10 { - table[z] = 0; - } - for row in board.iter() { - match row[i].to_digit(10) { - None => continue, - Some(idx) => { - if table[idx as usize] > 0 { - return false; - } else { - table[idx as usize] = 1 - } - } - } - } - } - for i in 0..3 { - for j in 0..3 { - for z in 1..10 { - table[z] = 0; - } - for row in 3 * i..3 * (i + 1) { - for column in 3 * j..3 * (j + 1) { - match board[row][column].to_digit(10) { - None => continue, - Some(idx) => { - if table[idx as usize] > 0 { - return false; - } else { - table[idx as usize] = 1 - } - } - } - } - } - } - } - true - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_36() { - assert_eq!( - Solution::is_valid_sudoku(vec![ - vec!['8', '3', '.', '.', '7', '.', '.', '.', '.'], - vec!['6', '.', '.', '1', '9', '5', '.', '.', '.'], - vec!['.', '9', '8', '.', '.', '.', '.', '6', '.'], - vec!['8', '.', '.', '.', '6', '.', '.', '.', '3'], - vec!['4', '.', '.', '8', '.', '3', '.', '.', '1'], - vec!['7', '.', '.', '.', '2', '.', '.', '.', '6'], - vec!['.', '6', '.', '.', '.', '.', '2', '8', '.'], - vec!['.', '.', '.', '4', '1', '9', '.', '.', '5'], - vec!['.', '.', '.', '.', '8', '.', '.', '7', '9'], - ]), - false - ); - assert_eq!( - Solution::is_valid_sudoku(vec![ - vec!['5', '3', '.', '.', '7', '.', '.', '.', '.'], - vec!['6', '.', '.', '1', '9', '5', '.', '.', '.'], - vec!['.', '9', '8', '.', '.', '.', '.', '6', '.'], - vec!['8', '.', '.', '.', '6', '.', '.', '.', '3'], - vec!['4', '.', '.', '8', '.', '3', '.', '.', '1'], - vec!['7', '.', '.', '.', '2', '.', '.', '.', '6'], - vec!['.', '6', '.', '.', '.', '.', '2', '8', '.'], - vec!['.', '.', '.', '4', '1', '9', '.', '.', '5'], - vec!['.', '.', '.', '.', '8', '.', '.', '7', '9'] - ]), - true - ); - } -} diff --git a/src/solution/s0037_sudoku_solver.rs b/src/solution/s0037_sudoku_solver.rs deleted file mode 100644 index d0187582..00000000 --- a/src/solution/s0037_sudoku_solver.rs +++ /dev/null @@ -1,51 +0,0 @@ -/** - * [37] Sudoku Solver - * - * Write a program to solve a Sudoku puzzle by filling the empty cells. - * - * A sudoku solution must satisfy all of the following rules: - * - *
    - * Each of the digits 1-9 must occur exactly once in each row. - * Each of the digits 1-9 must occur exactly once in each column. - * Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. - *
- * - * Empty cells are indicated by the character '.'. - * - *
- * A sudoku puzzle... - * - *
- * ...and its solution numbers marked in red. - * - * Note: - * - * - * The given board contain only digits 1-9 and the character '.'. - * You may assume that the given Sudoku puzzle will have a single unique solution. - * The given board size is always 9x9. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/sudoku-solver/ -// discuss: https://leetcode.com/problems/sudoku-solver/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO -impl Solution { - pub fn solve_sudoku(board: &mut Vec>) {} -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_37() {} -} diff --git a/src/solution/s0038_count_and_say.rs b/src/solution/s0038_count_and_say.rs deleted file mode 100644 index 6305b2a5..00000000 --- a/src/solution/s0038_count_and_say.rs +++ /dev/null @@ -1,81 +0,0 @@ -/** - * [38] Count and Say - * - * The count-and-say sequence is the sequence of integers with the first five terms as following: - * - * - * 1. 1 - * 2. 11 - * 3. 21 - * 4. 1211 - * 5. 111221 - * - * - * 1 is read off as "one 1" or 11.
- * 11 is read off as "two 1s" or 21.
- * 21 is read off as "one 2, then one 1" or 1211. - * - * Given an integer n where 1 <= n <= 30, generate the n^th term of the count-and-say sequence. - * - * Note: Each term of the sequence of integers will be represented as a string. - * - * - * - * Example 1: - * - * - * Input: 1 - * Output: "1" - * - * - * Example 2: - * - * - * Input: 4 - * Output: "1211" - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/count-and-say/ -// discuss: https://leetcode.com/problems/count-and-say/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::char::from_digit; -impl Solution { - pub fn count_and_say(n: i32) -> String { - let mut res = vec!['1']; - for _ in 0..n - 1 { - let mut temp = Vec::new(); - let mut i = 0_usize; - while i < res.len() { - let mut j = i + 1; - while j < res.len() && res[j] == res[i] { - j += 1; - } - temp.push(from_digit((j - i) as u32, 10).unwrap()); - temp.push(res[i]); - i = j; - } - res = temp; - } - res.iter().collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_38() { - assert_eq!(Solution::count_and_say(1), "1"); - assert_eq!(Solution::count_and_say(2), "11"); - assert_eq!(Solution::count_and_say(3), "21"); - assert_eq!(Solution::count_and_say(4), "1211"); - assert_eq!(Solution::count_and_say(5), "111221"); - } -} diff --git a/src/solution/s0039_combination_sum.rs b/src/solution/s0039_combination_sum.rs deleted file mode 100644 index b31e397e..00000000 --- a/src/solution/s0039_combination_sum.rs +++ /dev/null @@ -1,100 +0,0 @@ -/** - * [39] Combination Sum - * - * Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. - * - * The same repeated number may be chosen from candidates unlimited number of times. - * - * Note: - * - * - * All numbers (including target) will be positive integers. - * The solution set must not contain duplicate combinations. - * - * - * Example 1: - * - * - * Input: candidates = [2,3,6,7], target = 7, - * A solution set is: - * [ - * [7], - * [2,2,3] - * ] - * - * - * Example 2: - * - * - * Input: candidates = [2,3,5], target = 8, - * A solution set is: - * [ - * [2,2,2,2], - * [2,3,3], - * [3,5] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/combination-sum/ -// discuss: https://leetcode.com/problems/combination-sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn combination_sum(candidates: Vec, target: i32) -> Vec> { - let mut seq = candidates; - let mut res = Vec::new(); - seq.sort_unstable_by(|a, b| b.cmp(a)); - let mut vec = Vec::new(); - Solution::backtrack(&seq, target, vec, &mut res, 0); - res - } - - fn backtrack( - seq: &Vec, - target: i32, - mut curr: Vec, - result: &mut Vec>, - start_idx: usize, - ) { - for i in start_idx..seq.len() { - let item = seq[i]; - if target - item < 0 { - continue; - } - let mut new_vec = curr.clone(); - new_vec.push(item); - if target == item { - result.push(new_vec); - } else { - Solution::backtrack(seq, target - item, new_vec, result, i); - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_39() { - assert_eq!( - Solution::combination_sum(vec![1], 7), - vec![vec![1, 1, 1, 1, 1, 1, 1]] - ); - assert_eq!( - Solution::combination_sum(vec![2, 3, 6, 7], 7), - vec![vec![7], vec![3, 2, 2],] - ); - assert_eq!( - Solution::combination_sum(vec![2, 3, 5], 8), - vec![vec![5, 3], vec![3, 3, 2], vec![2, 2, 2, 2],] - ); - } -} diff --git a/src/solution/s0040_combination_sum_ii.rs b/src/solution/s0040_combination_sum_ii.rs deleted file mode 100644 index 0445bfb9..00000000 --- a/src/solution/s0040_combination_sum_ii.rs +++ /dev/null @@ -1,107 +0,0 @@ -/** - * [40] Combination Sum II - * - * Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. - * - * Each number in candidates may only be used once in the combination. - * - * Note: - * - * - * All numbers (including target) will be positive integers. - * The solution set must not contain duplicate combinations. - * - * - * Example 1: - * - * - * Input: candidates = [10,1,2,7,6,1,5], target = 8, - * A solution set is: - * [ - * [1, 7], - * [1, 2, 5], - * [2, 6], - * [1, 1, 6] - * ] - * - * - * Example 2: - * - * - * Input: candidates = [2,5,2,1,2], target = 5, - * A solution set is: - * [ - * [1,2,2], - * [5] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/combination-sum-ii/ -// discuss: https://leetcode.com/problems/combination-sum-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn combination_sum2(candidates: Vec, target: i32) -> Vec> { - let mut seq = candidates; - let mut res = Vec::new(); - seq.sort_unstable_by(|a, b| b.cmp(a)); - let mut vec = Vec::new(); - Solution::backtrack(&seq, target, vec, &mut res, 0); - res - } - - fn backtrack( - seq: &Vec, - target: i32, - mut curr: Vec, - result: &mut Vec>, - start_idx: usize, - ) { - let mut i = start_idx; - while i < seq.len() { - let item = seq[i]; - if target - item < 0 { - i += 1; - continue; - } - let mut new_vec = curr.clone(); - new_vec.push(item); - if target == item { - result.push(new_vec); - } else { - Solution::backtrack(seq, target - item, new_vec, result, i + 1); - } - // skip duplicate result - while i < seq.len() && seq[i] == item { - i += 1; - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_40() { - assert_eq!( - Solution::combination_sum2(vec![1, 1, 1, 1, 1, 1, 1], 7), - vec![vec![1, 1, 1, 1, 1, 1, 1]] - ); - assert_eq!( - Solution::combination_sum2(vec![10, 1, 2, 7, 6, 1, 5], 8), - vec![vec![7, 1], vec![6, 2], vec![6, 1, 1], vec![5, 2, 1],] - ); - assert_eq!( - Solution::combination_sum2(vec![2, 5, 2, 1, 2], 5), - vec![vec![5], vec![2, 2, 1],] - ); - } -} diff --git a/src/solution/s0041_first_missing_positive.rs b/src/solution/s0041_first_missing_positive.rs deleted file mode 100644 index 80cd8d8e..00000000 --- a/src/solution/s0041_first_missing_positive.rs +++ /dev/null @@ -1,91 +0,0 @@ -/** - * [41] First Missing Positive - * - * Given an unsorted integer array, find the smallest missing positive integer. - * - * Example 1: - * - * - * Input: [1,2,0] - * Output: 3 - * - * - * Example 2: - * - * - * Input: [3,4,-1,1] - * Output: 2 - * - * - * Example 3: - * - * - * Input: [7,8,9,11,12] - * Output: 1 - * - * - * Note: - * - * Your algorithm should run in O(n) time and uses constant extra space. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/first-missing-positive/ -// discuss: https://leetcode.com/problems/first-missing-positive/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn first_missing_positive(nums: Vec) -> i32 { - let mut nums = nums; - let len = nums.len(); - let mut i = 0; - let mut c = 0; - while i < len { - let num = nums[i]; - if num > 0 && num - 1 < (len as i32) { - c += 1; - nums.swap((num - 1) as usize, i); - if (num - 1) > (i as i32) && (num != nums[i]) { - continue; - } - } - i += 1; - } - println!("{}", c); - for (i, &num) in nums.iter().enumerate() { - if num != ((i + 1) as i32) { - return (i + 1) as i32; - } - } - return (len + 1) as i32; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_41() { - assert_eq!(Solution::first_missing_positive(vec![2, 2]), 1); - assert_eq!( - Solution::first_missing_positive(vec![12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2]), - 1 - ); - assert_eq!( - Solution::first_missing_positive(vec![2, 2, 2, 2, 2, 2, 2]), - 1 - ); - assert_eq!(Solution::first_missing_positive(vec![3, 4, -1, 1]), 2); - assert_eq!(Solution::first_missing_positive(vec![2, 1, 0]), 3); - assert_eq!(Solution::first_missing_positive(vec![7, 8, 9, 11, 12]), 1); - assert_eq!( - Solution::first_missing_positive(vec![7, 8, 1, 2, 3, 3, 3, 3, 3, 3, 3, -5, -7, 1234]), - 4 - ); - } -} diff --git a/src/solution/s0042_trapping_rain_water.rs b/src/solution/s0042_trapping_rain_water.rs deleted file mode 100644 index 9d961994..00000000 --- a/src/solution/s0042_trapping_rain_water.rs +++ /dev/null @@ -1,38 +0,0 @@ -/** - * [42] Trapping Rain Water - * - * 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. - * - *
- * 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! - * - * Example: - * - * - * Input: [0,1,0,2,1,0,1,3,2,1,2,1] - * Output: 6 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/trapping-rain-water/ -// discuss: https://leetcode.com/problems/trapping-rain-water/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO -impl Solution { - pub fn trap(height: Vec) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_42() {} -} diff --git a/src/solution/s0043_multiply_strings.rs b/src/solution/s0043_multiply_strings.rs deleted file mode 100644 index 8c487b8e..00000000 --- a/src/solution/s0043_multiply_strings.rs +++ /dev/null @@ -1,67 +0,0 @@ -/** - * [43] Multiply Strings - * - * Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. - * - * Example 1: - * - * - * Input: num1 = "2", num2 = "3" - * Output: "6" - * - * Example 2: - * - * - * Input: num1 = "123", num2 = "456" - * Output: "56088" - * - * - * Note: - * - *
    - * The length of both num1 and num2 is < 110. - * Both num1 and num2 contain only digits 0-9. - * Both num1 and num2 do not contain any leading zero, except the number 0 itself. - * You must not use any built-in BigInteger library or convert the inputs to integer directly. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/multiply-strings/ -// discuss: https://leetcode.com/problems/multiply-strings/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO -use std::char::from_digit; -use std::collections::VecDeque; -impl Solution { - pub fn multiply(num1: String, num2: String) -> String { - let mut num1: Vec = num1.chars().map(|ch| ch.to_digit(10).unwrap()).collect(); - let mut num2: Vec = num2.chars().map(|ch| ch.to_digit(10).unwrap()).collect(); - let mut buffer = VecDeque::with_capacity(num2.len() + 1); - let mut res: Vec = Vec::new(); - let mut carry = 0_u32; - num1.reverse(); - num2.reverse(); - for (i, multiplier) in num1.into_iter().enumerate() { - buffer - .pop_back() - .and_then(|digit| Some(res.push(from_digit(digit, 10).unwrap()))); - for &multiplicand in num2.iter() {} - } - res.reverse(); - res.into_iter().collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_43() {} -} diff --git a/src/solution/s0044_wildcard_matching.rs b/src/solution/s0044_wildcard_matching.rs deleted file mode 100644 index e875131a..00000000 --- a/src/solution/s0044_wildcard_matching.rs +++ /dev/null @@ -1,91 +0,0 @@ -/** - * [44] Wildcard Matching - * - * Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. - * - * - * '?' Matches any single character. - * '*' Matches any sequence of characters (including the empty sequence). - * - * - * The matching should cover the entire input string (not partial). - * - * Note: - * - * - * s could be empty and contains only lowercase letters a-z. - * p could be empty and contains only lowercase letters a-z, and characters like ? or *. - * - * - * Example 1: - * - * - * Input: - * s = "aa" - * p = "a" - * Output: false - * Explanation: "a" does not match the entire string "aa". - * - * - * Example 2: - * - * - * Input: - * s = "aa" - * p = "*" - * Output: true - * Explanation: '*' matches any sequence. - * - * - * Example 3: - * - * - * Input: - * s = "cb" - * p = "?a" - * Output: false - * Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. - * - * - * Example 4: - * - * - * Input: - * s = "adceb" - * p = "*a*b" - * Output: true - * Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". - * - * - * Example 5: - * - * - * Input: - * s = "acdcb" - * p = "a*c?b" - * Output: false - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/wildcard-matching/ -// discuss: https://leetcode.com/problems/wildcard-matching/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn is_match(s: String, p: String) -> bool { - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_44() {} -} diff --git a/src/solution/s0045_jump_game_ii.rs b/src/solution/s0045_jump_game_ii.rs deleted file mode 100644 index 3922e20b..00000000 --- a/src/solution/s0045_jump_game_ii.rs +++ /dev/null @@ -1,45 +0,0 @@ -/** - * [45] Jump Game II - * - * Given an array of non-negative integers, you are initially positioned at the first index of the array. - * - * Each element in the array represents your maximum jump length at that position. - * - * Your goal is to reach the last index in the minimum number of jumps. - * - * Example: - * - * - * Input: [2,3,1,1,4] - * Output: 2 - * Explanation: The minimum number of jumps to reach the last index is 2. - * Jump 1 step from index 0 to 1, then 3 steps to the last index. - * - * Note: - * - * You can assume that you can always reach the last index. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/jump-game-ii/ -// discuss: https://leetcode.com/problems/jump-game-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO: shortest path from backward -impl Solution { - pub fn jump(nums: Vec) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_45() {} -} diff --git a/src/solution/s0046_permutations.rs b/src/solution/s0046_permutations.rs deleted file mode 100644 index ef9354c8..00000000 --- a/src/solution/s0046_permutations.rs +++ /dev/null @@ -1,70 +0,0 @@ -/** - * [46] Permutations - * - * Given a collection of distinct integers, return all possible permutations. - * - * Example: - * - * - * Input: [1,2,3] - * Output: - * [ - * [1,2,3], - * [1,3,2], - * [2,1,3], - * [2,3,1], - * [3,1,2], - * [3,2,1] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/permutations/ -// discuss: https://leetcode.com/problems/permutations/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn permute(nums: Vec) -> Vec> { - if nums.len() <= 1 { - return vec![nums]; - } - nums.iter() - .flat_map(|&num| { - let mut sub = nums.clone().into_iter().filter(|&x| x != num).collect(); - Solution::permute(sub) - .into_iter() - .map(|vec| { - let mut vec = vec; - vec.push(num); - vec - }) - .collect::>>() - }) - .collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_46() { - assert_eq!( - Solution::permute(vec![1, 2, 3]), - vec![ - vec![3, 2, 1], - vec![2, 3, 1], - vec![3, 1, 2], - vec![1, 3, 2], - vec![2, 1, 3], - vec![1, 2, 3], - ] - ) - } -} diff --git a/src/solution/s0047_permutations_ii.rs b/src/solution/s0047_permutations_ii.rs deleted file mode 100644 index 7dceb55b..00000000 --- a/src/solution/s0047_permutations_ii.rs +++ /dev/null @@ -1,179 +0,0 @@ -/** - * [47] Permutations II - * - * Given a collection of numbers that might contain duplicates, return all possible unique permutations. - * - * Example: - * - * - * Input: [1,1,2] - * Output: - * [ - * [1,1,2], - * [1,2,1], - * [2,1,1] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/permutations-ii/ -// discuss: https://leetcode.com/problems/permutations-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn permute_unique(nums: Vec) -> Vec> { - let mut nums = nums; - nums.sort_unstable(); - Solution::permute(nums) - } - - fn permute(mut nums: Vec) -> Vec> { - if nums.len() <= 1 { - return vec![nums]; - } - let mut prev: Option = None; - let mut res = Vec::new(); - for (i, &num) in nums.iter().enumerate() { - if prev.is_some() && prev.unwrap() == num { - continue; - } else { - prev = Some(num) - } - let mut sub = nums.clone(); - sub.remove(i); - let mut permutations: Vec> = Solution::permute(sub) - .into_iter() - .map(|x| { - let mut x = x; - x.push(num); - x - }) - .collect(); - res.append(&mut permutations); - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_47() { - assert_eq!( - Solution::permute(vec![1, 1, 2]), - vec![vec![2, 1, 1], vec![1, 2, 1], vec![1, 1, 2],] - ); - assert_eq!(Solution::permute(vec![1, 1, 1]), vec![vec![1, 1, 1],]); - assert_eq!( - Solution::permute(vec![1, 1, 1, 2]), - vec![ - vec![2, 1, 1, 1], - vec![1, 2, 1, 1], - vec![1, 1, 2, 1], - vec![1, 1, 1, 2], - ] - ); - assert_eq!( - Solution::permute(vec![1, 1, 2, 2, 3, 3]), - vec![ - vec![3, 3, 2, 2, 1, 1], - vec![3, 2, 3, 2, 1, 1], - vec![2, 3, 3, 2, 1, 1], - vec![3, 2, 2, 3, 1, 1], - vec![2, 3, 2, 3, 1, 1], - vec![2, 2, 3, 3, 1, 1], - vec![3, 3, 2, 1, 2, 1], - vec![3, 2, 3, 1, 2, 1], - vec![2, 3, 3, 1, 2, 1], - vec![3, 3, 1, 2, 2, 1], - vec![3, 1, 3, 2, 2, 1], - vec![1, 3, 3, 2, 2, 1], - vec![3, 2, 1, 3, 2, 1], - vec![2, 3, 1, 3, 2, 1], - vec![3, 1, 2, 3, 2, 1], - vec![1, 3, 2, 3, 2, 1], - vec![2, 1, 3, 3, 2, 1], - vec![1, 2, 3, 3, 2, 1], - vec![3, 2, 2, 1, 3, 1], - vec![2, 3, 2, 1, 3, 1], - vec![2, 2, 3, 1, 3, 1], - vec![3, 2, 1, 2, 3, 1], - vec![2, 3, 1, 2, 3, 1], - vec![3, 1, 2, 2, 3, 1], - vec![1, 3, 2, 2, 3, 1], - vec![2, 1, 3, 2, 3, 1], - vec![1, 2, 3, 2, 3, 1], - vec![2, 2, 1, 3, 3, 1], - vec![2, 1, 2, 3, 3, 1], - vec![1, 2, 2, 3, 3, 1], - vec![3, 3, 2, 1, 1, 2], - vec![3, 2, 3, 1, 1, 2], - vec![2, 3, 3, 1, 1, 2], - vec![3, 3, 1, 2, 1, 2], - vec![3, 1, 3, 2, 1, 2], - vec![1, 3, 3, 2, 1, 2], - vec![3, 2, 1, 3, 1, 2], - vec![2, 3, 1, 3, 1, 2], - vec![3, 1, 2, 3, 1, 2], - vec![1, 3, 2, 3, 1, 2], - vec![2, 1, 3, 3, 1, 2], - vec![1, 2, 3, 3, 1, 2], - vec![3, 3, 1, 1, 2, 2], - vec![3, 1, 3, 1, 2, 2], - vec![1, 3, 3, 1, 2, 2], - vec![3, 1, 1, 3, 2, 2], - vec![1, 3, 1, 3, 2, 2], - vec![1, 1, 3, 3, 2, 2], - vec![3, 2, 1, 1, 3, 2], - vec![2, 3, 1, 1, 3, 2], - vec![3, 1, 2, 1, 3, 2], - vec![1, 3, 2, 1, 3, 2], - vec![2, 1, 3, 1, 3, 2], - vec![1, 2, 3, 1, 3, 2], - vec![3, 1, 1, 2, 3, 2], - vec![1, 3, 1, 2, 3, 2], - vec![1, 1, 3, 2, 3, 2], - vec![2, 1, 1, 3, 3, 2], - vec![1, 2, 1, 3, 3, 2], - vec![1, 1, 2, 3, 3, 2], - vec![3, 2, 2, 1, 1, 3], - vec![2, 3, 2, 1, 1, 3], - vec![2, 2, 3, 1, 1, 3], - vec![3, 2, 1, 2, 1, 3], - vec![2, 3, 1, 2, 1, 3], - vec![3, 1, 2, 2, 1, 3], - vec![1, 3, 2, 2, 1, 3], - vec![2, 1, 3, 2, 1, 3], - vec![1, 2, 3, 2, 1, 3], - vec![2, 2, 1, 3, 1, 3], - vec![2, 1, 2, 3, 1, 3], - vec![1, 2, 2, 3, 1, 3], - vec![3, 2, 1, 1, 2, 3], - vec![2, 3, 1, 1, 2, 3], - vec![3, 1, 2, 1, 2, 3], - vec![1, 3, 2, 1, 2, 3], - vec![2, 1, 3, 1, 2, 3], - vec![1, 2, 3, 1, 2, 3], - vec![3, 1, 1, 2, 2, 3], - vec![1, 3, 1, 2, 2, 3], - vec![1, 1, 3, 2, 2, 3], - vec![2, 1, 1, 3, 2, 3], - vec![1, 2, 1, 3, 2, 3], - vec![1, 1, 2, 3, 2, 3], - vec![2, 2, 1, 1, 3, 3], - vec![2, 1, 2, 1, 3, 3], - vec![1, 2, 2, 1, 3, 3], - vec![2, 1, 1, 2, 3, 3], - vec![1, 2, 1, 2, 3, 3], - vec![1, 1, 2, 2, 3, 3] - ] - ); - } -} diff --git a/src/solution/s0048_rotate_image.rs b/src/solution/s0048_rotate_image.rs deleted file mode 100644 index 6f6fdffa..00000000 --- a/src/solution/s0048_rotate_image.rs +++ /dev/null @@ -1,122 +0,0 @@ -/** - * [48] Rotate Image - * - * You are given an n x n 2D matrix representing an image. - * - * Rotate the image by 90 degrees (clockwise). - * - * Note: - * - * You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. - * - * Example 1: - * - * - * Given input matrix = - * [ - * [1,2,3], - * [4,5,6], - * [7,8,9] - * ], - * - * rotate the input matrix in-place such that it becomes: - * [ - * [7,4,1], - * [8,5,2], - * [9,6,3] - * ] - * - * - * Example 2: - * - * - * Given input matrix = - * [ - * [ 5, 1, 9,11], - * [ 2, 4, 8,10], - * [13, 3, 6, 7], - * [15,14,12,16] - * ], - * - * rotate the input matrix in-place such that it becomes: - * [ - * [15,13, 2, 5], - * [14, 3, 4, 1], - * [12, 6, 8, 9], - * [16, 7,10,11] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/rotate-image/ -// discuss: https://leetcode.com/problems/rotate-image/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// x,y -> y,n-x 2-dimension vector rotate -90 degree: -// ^ x 0 1 y -// | | * = -// v y -1 0 -x -// n-y,x <- n-x,n-y if we consider axis transform, then: rotate(x, y) = (y, -x + n) - -// we only need to iterate a 1/4 corner matrix, for odd matrix, we take an extra part in x direction -// -// even: -// -// x x o o -// x x o o -// o o o o -// o o o o -// -// odd: -// -// x x o o o -// x x o o o -// x x o o o -// o o o o o -// o o o o o - -impl Solution { - pub fn rotate(matrix: &mut Vec>) { - let mut matrix = matrix; - let (len, n) = (matrix.len(), matrix.len() - 1); - for x in 0..len / 2 { - for y in 0..(len + 1) / 2 { - let temp = matrix[x][y]; - matrix[x][y] = matrix[n - y][x]; - matrix[n - y][x] = matrix[n - x][n - y]; - matrix[n - x][n - y] = matrix[y][n - x]; - matrix[y][n - x] = temp; - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_48() { - let mut matrix = vec![ - vec![5, 1, 9, 11], - vec![2, 4, 8, 10], - vec![13, 3, 6, 7], - vec![15, 14, 12, 16], - ]; - Solution::rotate(&mut matrix); - assert_eq!( - matrix, - vec![ - vec![15, 13, 2, 5], - vec![14, 3, 4, 1], - vec![12, 6, 8, 9], - vec![16, 7, 10, 11] - ] - ); - } -} diff --git a/src/solution/s0049_group_anagrams.rs b/src/solution/s0049_group_anagrams.rs deleted file mode 100644 index 64200ea3..00000000 --- a/src/solution/s0049_group_anagrams.rs +++ /dev/null @@ -1,67 +0,0 @@ -/** - * [49] Group Anagrams - * - * Given an array of strings, group anagrams together. - * - * Example: - * - * - * Input: ["eat", "tea", "tan", "ate", "nat", "bat"], - * Output: - * [ - * ["ate","eat","tea"], - * ["nat","tan"], - * ["bat"] - * ] - * - * Note: - * - * - * All inputs will be in lowercase. - * The order of your output does not matter. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/group-anagrams/ -// discuss: https://leetcode.com/problems/group-anagrams/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::HashMap; -impl Solution { - pub fn group_anagrams(strs: Vec) -> Vec> { - let mut map = HashMap::new(); - for s in strs.into_iter() { - let mut key = [0; 26]; - for ch in s.chars() { - key[(ch as u32 - 'a' as u32) as usize] += 1; - } - map.entry(key).or_insert(Vec::new()).push(s); - } - map.into_iter().map(|(_, v)| v).collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - use std::collections::HashSet; - // TODO: implement arbitrary match macro - #[test] - #[ignore] - fn test_49() { - assert_eq!( - Solution::group_anagrams(vec_string!["eat", "tea", "tan", "ate", "nat", "bat"]), - vec![ - vec_string!["tan", "nat"], - vec_string!["bat"], - vec_string!["eat", "ate", "tea"], - ] - ); - } -} diff --git a/src/solution/s0050_powx_n.rs b/src/solution/s0050_powx_n.rs deleted file mode 100644 index 3e2e9b3e..00000000 --- a/src/solution/s0050_powx_n.rs +++ /dev/null @@ -1,64 +0,0 @@ -/** - * [50] Pow(x, n) - * - * Implement pow(x, n), which calculates x raised to the power n (x^n). - * - * Example 1: - * - * - * Input: 2.00000, 10 - * Output: 1024.00000 - * - * - * Example 2: - * - * - * Input: 2.10000, 3 - * Output: 9.26100 - * - * - * Example 3: - * - * - * Input: 2.00000, -2 - * Output: 0.25000 - * Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25 - * - * - * Note: - * - * - * -100.0 < x < 100.0 - * n is a 32-bit signed integer, within the range [-2^31, 2^31 - 1] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/powx-n/ -// discuss: https://leetcode.com/problems/powx-n/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn my_pow(x: f64, n: i32) -> f64 { - x.powi(n) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_50() { - assert_eq!(Solution::my_pow(2.0, -2), 0.25); - assert_eq!(Solution::my_pow(2.0, 4), 16.0); - assert_eq!(Solution::my_pow(2.0, 5), 32.0); - assert_eq!(Solution::my_pow(2.0, 1), 2.0); - assert_eq!(Solution::my_pow(2.0, -1), 0.5); - assert_eq!(Solution::my_pow(2.0, 10), 1024.0); - } -} diff --git a/src/solution/s0051_n_queens.rs b/src/solution/s0051_n_queens.rs deleted file mode 100644 index d78435a9..00000000 --- a/src/solution/s0051_n_queens.rs +++ /dev/null @@ -1,109 +0,0 @@ -/** - * [51] N-Queens - * - * The n-queens puzzle is the problem of placing n queens on an n*n chessboard such that no two queens attack each other. - * - * - * - * Given an integer n, return all distinct solutions to the n-queens puzzle. - * - * Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. - * - * Example: - * - * - * Input: 4 - * Output: [ - * [".Q..", // Solution 1 - * "...Q", - * "Q...", - * "..Q."], - * - * ["..Q.", // Solution 2 - * "Q...", - * "...Q", - * ".Q.."] - * ] - * Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/n-queens/ -// discuss: https://leetcode.com/problems/n-queens/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn solve_n_queens(n: i32) -> Vec> { - let mut board = vec![vec!['.'; n as usize]; n as usize]; - let mut solution = Vec::new(); - Solution::schedule_queens(&mut board, &mut solution, n as usize, 0); - solution - } - - fn schedule_queens( - board: &mut Vec>, - solution: &mut Vec>, - len: usize, - row: usize, - ) { - for col in 0..len { - if !Solution::collision(&board, len, row, col) { - board[row][col] = 'Q'; - if row == len - 1 { - solution.push(board.iter().map(|vec| vec.iter().collect()).collect()); - } else { - Solution::schedule_queens(board, solution, len, row + 1); - } - board[row][col] = '.'; - } - } - } - - #[inline(always)] - fn collision(board: &Vec>, len: usize, x: usize, y: usize) -> bool { - for i in 0..x { - if board[i][y] == 'Q' { - return true; - } - } - let (mut i, mut j) = (x as i32 - 1, y as i32 - 1); - while i >= 0 && j >= 0 { - if board[i as usize][j as usize] == 'Q' { - return true; - } - i -= 1; - j -= 1; - } - let (mut i, mut j) = (x as i32 - 1, y as i32 + 1); - while i >= 0 && j < len as i32 { - if board[i as usize][j as usize] == 'Q' { - return true; - } - i -= 1; - j += 1; - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_51() { - assert_eq!( - Solution::solve_n_queens(4), - vec![ - vec![".Q..", "...Q", "Q...", "..Q."], - vec!["..Q.", "Q...", "...Q", ".Q.."] - ] - ); - assert_eq!(Solution::solve_n_queens(8).len(), 92); - } -} diff --git a/src/solution/s0052_n_queens_ii.rs b/src/solution/s0052_n_queens_ii.rs deleted file mode 100644 index 7c9b1987..00000000 --- a/src/solution/s0052_n_queens_ii.rs +++ /dev/null @@ -1,99 +0,0 @@ -/** - * [52] N-Queens II - * - * The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. - * - * - * - * Given an integer n, return the number of distinct solutions to the n-queens puzzle. - * - * Example: - * - * - * Input: 4 - * Output: 2 - * Explanation: There are two distinct solutions to the 4-queens puzzle as shown below. - * [ - * [".Q..", // Solution 1 - * "...Q", - * "Q...", - * "..Q."], - * - * ["..Q.", // Solution 2 - * "Q...", - * "...Q", - * ".Q.."] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/n-queens-ii/ -// discuss: https://leetcode.com/problems/n-queens-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn total_n_queens(n: i32) -> i32 { - let mut board = vec![vec!['.'; n as usize]; n as usize]; - let mut num = 0; - Solution::schedule_queens(&mut board, &mut num, n as usize, 0); - num - } - - fn schedule_queens(board: &mut Vec>, num: &mut i32, len: usize, row: usize) { - for col in 0..len { - if !Solution::collision(&board, len, row, col) { - board[row][col] = 'Q'; - if row == len - 1 { - *num += 1; - } else { - Solution::schedule_queens(board, num, len, row + 1); - } - board[row][col] = '.'; - } - } - } - - #[inline(always)] - fn collision(board: &Vec>, len: usize, x: usize, y: usize) -> bool { - for i in 0..x { - if board[i][y] == 'Q' { - return true; - } - } - let (mut i, mut j) = (x as i32 - 1, y as i32 - 1); - while i >= 0 && j >= 0 { - if board[i as usize][j as usize] == 'Q' { - return true; - } - i -= 1; - j -= 1; - } - let (mut i, mut j) = (x as i32 - 1, y as i32 + 1); - while i >= 0 && j < len as i32 { - if board[i as usize][j as usize] == 'Q' { - return true; - } - i -= 1; - j += 1; - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_52() { - assert_eq!(Solution::total_n_queens(4), 2); - assert_eq!(Solution::total_n_queens(8), 92); - assert_eq!(Solution::total_n_queens(13), 73712); - // assert_eq!(Solution::total_n_queens(14), 365596); - } -} diff --git a/src/solution/s0053_maximum_subarray.rs b/src/solution/s0053_maximum_subarray.rs deleted file mode 100644 index 7967fb00..00000000 --- a/src/solution/s0053_maximum_subarray.rs +++ /dev/null @@ -1,57 +0,0 @@ -/** - * [53] Maximum Subarray - * - * Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. - * - * Example: - * - * - * Input: [-2,1,-3,4,-1,2,1,-5,4], - * Output: 6 - * Explanation: [4,-1,2,1] has the largest sum = 6. - * - * - * Follow up: - * - * If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/maximum-subarray/ -// discuss: https://leetcode.com/problems/maximum-subarray/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn max_sub_array(nums: Vec) -> i32 { - let mut j = 0_usize; - let mut max = i32::min_value(); - let mut curr = 0; - for j in 0..nums.len() { - curr += nums[j]; - max = i32::max(max, curr); - if curr <= 0 { - curr = 0; - } - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_53() { - assert_eq!( - Solution::max_sub_array(vec![-2, 1, -3, 4, -1, 2, 1, -5, 4]), - 6 - ); - assert_eq!(Solution::max_sub_array(vec![-8]), -8); - assert_eq!(Solution::max_sub_array(vec![-8, -2]), -2); - } -} diff --git a/src/solution/s0054_spiral_matrix.rs b/src/solution/s0054_spiral_matrix.rs deleted file mode 100644 index ac90b769..00000000 --- a/src/solution/s0054_spiral_matrix.rs +++ /dev/null @@ -1,101 +0,0 @@ -/** - * [54] Spiral Matrix - * - * Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. - * - * Example 1: - * - * - * Input: - * [ - * [ 1, 2, 3 ], - * [ 4, 5, 6 ], - * [ 7, 8, 9 ] - * ] - * Output: [1,2,3,6,9,8,7,4,5] - * - * - * Example 2: - * - * Input: - * [ - * [1, 2, 3, 4], - * [5, 6, 7, 8], - * [9,10,11,12] - * ] - * Output: [1,2,3,4,8,12,11,10,9,5,6,7] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/spiral-matrix/ -// discuss: https://leetcode.com/problems/spiral-matrix/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn spiral_order(matrix: Vec>) -> Vec { - let mut res = Vec::new(); - if matrix.len() < 1 { - return res; - } - let (height, width) = (matrix.len(), matrix[0].len()); - let (mut x_min, mut x_max, mut y_min, mut y_max) = (0, height, 0, width); - loop { - for y in y_min..y_max { - res.push(matrix[x_min][y]) - } - x_min += 1; - if x_min == x_max { - break; - } - for x in x_min..x_max { - res.push(matrix[x][y_max - 1]) - } - y_max -= 1; - if y_min == y_max { - break; - } - for y in (y_min..y_max).rev() { - res.push(matrix[x_max - 1][y]) - } - x_max -= 1; - if x_min == x_max { - break; - } - for x in (x_min..x_max).rev() { - res.push(matrix[x][y_min]) - } - y_min += 1; - if y_min == y_max { - break; - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_54() { - assert_eq!( - Solution::spiral_order(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]]), - vec![1, 2, 3, 6, 9, 8, 7, 4, 5] - ); - assert_eq!(Solution::spiral_order(vec![vec![1, 2, 3]]), vec![1, 2, 3]); - assert_eq!( - Solution::spiral_order(vec![vec![1], vec![2], vec![3],]), - vec![1, 2, 3] - ); - assert_eq!(Solution::spiral_order(vec![vec![1],]), vec![1]); - assert_eq!( - Solution::spiral_order(vec![vec![1, 2], vec![4, 5],]), - vec![1, 2, 5, 4] - ); - } -} diff --git a/src/solution/s0055_jump_game.rs b/src/solution/s0055_jump_game.rs deleted file mode 100644 index 8dc35842..00000000 --- a/src/solution/s0055_jump_game.rs +++ /dev/null @@ -1,66 +0,0 @@ -/** - * [55] Jump Game - * - * Given an array of non-negative integers, you are initially positioned at the first index of the array. - * - * Each element in the array represents your maximum jump length at that position. - * - * Determine if you are able to reach the last index. - * - * Example 1: - * - * - * Input: [2,3,1,1,4] - * Output: true - * Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. - * - * - * Example 2: - * - * - * Input: [3,2,1,0,4] - * Output: false - * Explanation: You will always arrive at index 3 no matter what. Its maximum - * jump length is 0, which makes it impossible to reach the last index. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/jump-game/ -// discuss: https://leetcode.com/problems/jump-game/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn can_jump(nums: Vec) -> bool { - let mut max_idx = 0_usize; - let mut start = 0_usize; - while start < nums.len() && start <= max_idx { - max_idx = usize::max(start + nums[start] as usize, max_idx); - start += 1; - } - return max_idx >= (nums.len() - 1); - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_55() { - assert_eq!(Solution::can_jump(vec![2, 3, 1, 1, 4]), true); - assert_eq!(Solution::can_jump(vec![3, 2, 1, 0, 4]), false); - assert_eq!(Solution::can_jump(vec![2, 3, 1, 1, 0, 0, 0, 4]), false); - assert_eq!(Solution::can_jump(vec![8, 3, 1, 1, 0, 0, 0, 4]), true); - assert_eq!(Solution::can_jump(vec![0]), true); - assert_eq!(Solution::can_jump(vec![1, 1, 2, 2, 0, 1, 1]), true); - assert_eq!( - Solution::can_jump(vec![1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]), - true - ); - } -} diff --git a/src/solution/s0056_merge_intervals.rs b/src/solution/s0056_merge_intervals.rs deleted file mode 100644 index 108c043b..00000000 --- a/src/solution/s0056_merge_intervals.rs +++ /dev/null @@ -1,85 +0,0 @@ -/** - * [56] Merge Intervals - * - * Given a collection of intervals, merge all overlapping intervals. - * - * Example 1: - * - * - * Input: [[1,3],[2,6],[8,10],[15,18]] - * Output: [[1,6],[8,10],[15,18]] - * Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. - * - * - * Example 2: - * - * - * Input: [[1,4],[4,5]] - * Output: [[1,5]] - * Explanation: Intervals [1,4] and [4,5] are considered overlapping. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/merge-intervals/ -// discuss: https://leetcode.com/problems/merge-intervals/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for an interval. -#[derive(Debug, PartialEq, Eq)] -pub struct Interval { - pub start: i32, - pub end: i32, -} - -impl Interval { - #[inline] - pub fn new(start: i32, end: i32) -> Self { - Interval { start, end } - } -} -impl Solution { - pub fn merge(intervals: Vec) -> Vec { - let mut intervals = intervals; - intervals.sort_unstable_by_key(|interval| interval.start); - let mut result: Vec = Vec::new(); - for interval in intervals.into_iter() { - match result.last_mut() { - Some(mut last_inter) => { - if last_inter.end >= interval.start { - last_inter.end = i32::max(last_inter.end, interval.end); - continue; - } - } - None => {} - } - result.push(interval); - } - result - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_56() { - assert_eq!( - Solution::merge(vec![ - Interval::new(1, 3), - Interval::new(2, 6), - Interval::new(8, 10), - Interval::new(15, 18) - ]), - vec![ - Interval::new(1, 6), - Interval::new(8, 10), - Interval::new(15, 18) - ] - ); - } -} diff --git a/src/solution/s0057_insert_interval.rs b/src/solution/s0057_insert_interval.rs deleted file mode 100644 index 0afe62b4..00000000 --- a/src/solution/s0057_insert_interval.rs +++ /dev/null @@ -1,126 +0,0 @@ -/** - * [57] Insert Interval - * - * Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). - * - * You may assume that the intervals were initially sorted according to their start times. - * - * Example 1: - * - * - * Input: intervals = [[1,3],Interval::new(6,9)], newInterval = [2,5] - * Output: [[1,5],[6,9]] - * - * - * Example 2: - * - * - * Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] - * Output: [[1,2],[3,10],[12,16]] - * Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/insert-interval/ -// discuss: https://leetcode.com/problems/insert-interval/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for an interval. -#[derive(Debug, PartialEq, Eq)] -pub struct Interval { - pub start: i32, - pub end: i32, -} - -impl Interval { - #[inline] - pub fn new(start: i32, end: i32) -> Self { - Interval { start, end } - } -} -impl Solution { - pub fn insert(intervals: Vec, new_interval: Interval) -> Vec { - let mut result = Vec::new(); - let mut new_interval = new_interval; - let mut inserting = false; - let mut inserted = false; - for interval in intervals.into_iter() { - if new_interval.start <= interval.end && !inserted { - inserting = true; - } - if inserting { - if new_interval.end >= interval.start { - new_interval.start = i32::min(new_interval.start, interval.start); - new_interval.end = i32::max(new_interval.end, interval.end); - } else { - result.push(Interval::new(new_interval.start, new_interval.end)); - inserting = false; - inserted = true; - } - } - if !inserting { - result.push(interval); - } - } - if !inserted { - result.push(new_interval); - } - result - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_57() { - assert_eq!( - Solution::insert( - vec![Interval::new(1, 3), Interval::new(6, 9)], - Interval::new(2, 5) - ), - vec![Interval::new(1, 5), Interval::new(6, 9)] - ); - assert_eq!( - Solution::insert( - vec![ - Interval::new(1, 2), - Interval::new(3, 5), - Interval::new(6, 7), - Interval::new(8, 10), - Interval::new(12, 16) - ], - Interval::new(4, 8) - ), - vec![ - Interval::new(1, 2), - Interval::new(3, 10), - Interval::new(12, 16) - ] - ); - assert_eq!( - Solution::insert(vec![Interval::new(3, 4)], Interval::new(1, 2)), - vec![Interval::new(1, 2), Interval::new(3, 4)] - ); - assert_eq!( - Solution::insert(vec![Interval::new(1, 2)], Interval::new(3, 4)), - vec![Interval::new(1, 2), Interval::new(3, 4)] - ); - assert_eq!( - Solution::insert(vec![Interval::new(1, 2)], Interval::new(2, 3)), - vec![Interval::new(1, 3)] - ); - assert_eq!( - Solution::insert( - vec![Interval::new(1, 2), Interval::new(3, 4)], - Interval::new(0, 6) - ), - vec![Interval::new(0, 6)] - ); - } -} diff --git a/src/solution/s0058_length_of_last_word.rs b/src/solution/s0058_length_of_last_word.rs deleted file mode 100644 index 4889c739..00000000 --- a/src/solution/s0058_length_of_last_word.rs +++ /dev/null @@ -1,55 +0,0 @@ -/** - * [58] Length of Last Word - * - * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. - * - * If the last word does not exist, return 0. - * - * Note: A word is defined as a character sequence consists of non-space characters only. - * - * Example: - * - * Input: "Hello World" - * Output: 5 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/length-of-last-word/ -// discuss: https://leetcode.com/problems/length-of-last-word/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn length_of_last_word(s: String) -> i32 { - let seq: Vec = s.chars().rev().collect(); - let mut result = 0; - let mut find = false; - for ch in seq { - if ch == ' ' && find { - break; - } - if ch != ' ' { - find = true; - result += 1; - } - } - result - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_58() { - assert_eq!(Solution::length_of_last_word("Hello World".to_owned()), 5); - assert_eq!(Solution::length_of_last_word(" ".to_owned()), 0); - assert_eq!(Solution::length_of_last_word("".to_owned()), 0); - assert_eq!(Solution::length_of_last_word(" rrrrr ".to_owned()), 5); - } -} diff --git a/src/solution/s0059_spiral_matrix_ii.rs b/src/solution/s0059_spiral_matrix_ii.rs deleted file mode 100644 index d54f57b4..00000000 --- a/src/solution/s0059_spiral_matrix_ii.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [59] Spiral Matrix II - * - * Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. - * - * Example: - * - * - * Input: 3 - * Output: - * [ - * [ 1, 2, 3 ], - * [ 8, 9, 4 ], - * [ 7, 6, 5 ] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/spiral-matrix-ii/ -// discuss: https://leetcode.com/problems/spiral-matrix-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn generate_matrix(n: i32) -> Vec> { - let mut res = vec![vec![0; n as usize]; n as usize]; - if n < 1 { - return res; - } - let (mut x_min, mut x_max, mut y_min, mut y_max) = (0, n as usize, 0, n as usize); - let mut i = 1; - loop { - for y in y_min..y_max { - res[x_min][y] = i; - i += 1; - } - x_min += 1; - if x_min == x_max { - break; - } - for x in x_min..x_max { - res[x][y_max - 1] = i; - i += 1; - } - y_max -= 1; - if y_min == y_max { - break; - } - for y in (y_min..y_max).rev() { - res[x_max - 1][y] = i; - i += 1; - } - x_max -= 1; - if x_min == x_max { - break; - } - for x in (x_min..x_max).rev() { - res[x][y_min] = i; - i += 1; - } - y_min += 1; - if y_min == y_max { - break; - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_59() { - assert_eq!(Solution::generate_matrix(1), vec![vec![1]]); - assert_eq!(Solution::generate_matrix(2), vec![vec![1, 2], vec![4, 3]]); - assert_eq!( - Solution::generate_matrix(3), - vec![vec![1, 2, 3], vec![8, 9, 4], vec![7, 6, 5],] - ); - } -} diff --git a/src/solution/s0060_permutation_sequence.rs b/src/solution/s0060_permutation_sequence.rs deleted file mode 100644 index 0136a0b4..00000000 --- a/src/solution/s0060_permutation_sequence.rs +++ /dev/null @@ -1,76 +0,0 @@ -/** - * [60] Permutation Sequence - * - * The set [1,2,3,...,n] contains a total of n! unique permutations. - * - * By listing and labeling all of the permutations in order, we get the following sequence for n = 3: - * - *
    - * "123" - * "132" - * "213" - * "231" - * "312" - * "321" - *
- * - * Given n and k, return the k^th permutation sequence. - * - * Note: - * - * - * Given n will be between 1 and 9 inclusive. - * Given k will be between 1 and n! inclusive. - * - * - * Example 1: - * - * - * Input: n = 3, k = 3 - * Output: "213" - * - * - * Example 2: - * - * - * Input: n = 4, k = 9 - * Output: "2314" - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/permutation-sequence/ -// discuss: https://leetcode.com/problems/permutation-sequence/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// target: split k = i! + j! + ... -use std::char::from_digit; -impl Solution { - pub fn get_permutation(n: i32, k: i32) -> String { - let factorials = [0, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]; - let mut k = k; - let mut i = n; - let mut res = String::new(); - while i > 0 { - if k > factorials[i as usize] { - let round = k / factorials[i as usize]; - if round >= n {} - } else { - i -= 1; - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_60() {} -} diff --git a/src/solution/s0061_rotate_list.rs b/src/solution/s0061_rotate_list.rs deleted file mode 100644 index bbfb059f..00000000 --- a/src/solution/s0061_rotate_list.rs +++ /dev/null @@ -1,50 +0,0 @@ -/** - * [61] Rotate List - * - * Given a linked list, rotate the list to the right by k places, where k is non-negative. - * - * Example 1: - * - * - * Input: 1->2->3->4->5->NULL, k = 2 - * Output: 4->5->1->2->3->NULL - * Explanation: - * rotate 1 steps to the right: 5->1->2->3->4->NULL - * rotate 2 steps to the right: 4->5->1->2->3->NULL - * - * - * Example 2: - * - * - * Input: 0->1->2->NULL, k = 4 - * Output: 2->0->1->NULL - * Explanation: - * rotate 1 steps to the right: 2->0->1->NULL - * rotate 2 steps to the right: 1->2->0->NULL - * rotate 3 steps to the right: 0->1->2->NULL - * rotate 4 steps to the right: 2->0->1->NULL - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/rotate-list/ -// discuss: https://leetcode.com/problems/rotate-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn rotate_right(head: Option>, k: i32) -> Option> { - None - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_61() {} -} diff --git a/src/solution/s0062_unique_paths.rs b/src/solution/s0062_unique_paths.rs deleted file mode 100644 index 3a158326..00000000 --- a/src/solution/s0062_unique_paths.rs +++ /dev/null @@ -1,80 +0,0 @@ -/** - * [62] Unique Paths - * - * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). - * - * The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). - * - * How many possible unique paths are there? - * - *
- * Above is a 7 x 3 grid. How many possible unique paths are there? - * - * Note: m and n will be at most 100. - * - * Example 1: - * - * - * Input: m = 3, n = 2 - * Output: 3 - * Explanation: - * From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: - * 1. Right -> Right -> Down - * 2. Right -> Down -> Right - * 3. Down -> Right -> Right - * - * - * Example 2: - * - * - * Input: m = 7, n = 3 - * Output: 28 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/unique-paths/ -// discuss: https://leetcode.com/problems/unique-paths/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// its high school math: C(r,n) = n! / r!(n-r)! ...are you fxxking kidding me? -// ...high school math will attempt to i32 overflow, we have to do it clever -impl Solution { - pub fn unique_paths(m: i32, n: i32) -> i32 { - let (m, n) = ((m - 1) as u64, (n - 1) as u64); - let sum = m + n; - (Solution::partial_factorial(u64::max(m, n), sum) - / Solution::partial_factorial(0, u64::min(m, n))) as i32 - } - - #[inline(always)] - pub fn partial_factorial(start: u64, mut end: u64) -> u64 { - if start > end { - unreachable!() - } - let mut res = 1; - while end > start { - println!("{}", end); - res *= end; - end -= 1; - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_62() { - assert_eq!(Solution::unique_paths(7, 3), 28); - assert_eq!(Solution::unique_paths(3, 7), 28); - assert_eq!(Solution::unique_paths(1, 1), 1); - assert_eq!(Solution::unique_paths(2, 2), 2); - assert_eq!(Solution::unique_paths(36, 7), 4496388); - } -} diff --git a/src/solution/s0063_unique_paths_ii.rs b/src/solution/s0063_unique_paths_ii.rs deleted file mode 100644 index 04d84911..00000000 --- a/src/solution/s0063_unique_paths_ii.rs +++ /dev/null @@ -1,111 +0,0 @@ -/** - * [63] Unique Paths II - * - * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). - * - * The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). - * - * Now consider if some obstacles are added to the grids. How many unique paths would there be? - * - * - * - * An obstacle and empty space is marked as 1 and 0 respectively in the grid. - * - * Note: m and n will be at most 100. - * - * Example 1: - * - * - * Input: - * [ - * [0,0,0], - * [0,1,0], - * [0,0,0] - * ] - * Output: 2 - * Explanation: - * There is one obstacle in the middle of the 3x3 grid above. - * There are two ways to reach the bottom-right corner: - * 1. Right -> Right -> Down -> Down - * 2. Down -> Down -> Right -> Right - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/unique-paths-ii/ -// discuss: https://leetcode.com/problems/unique-paths-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Bottom-Up DP -impl Solution { - pub fn unique_paths_with_obstacles(obstacle_grid: Vec>) -> i32 { - let (height, width) = (obstacle_grid.len(), obstacle_grid[0].len()); - let mut paths: Vec> = vec![vec![0; width]; height]; - if obstacle_grid[0][0] != 1 { - paths[0][0] = 1; - } - let mut step = 1; - while step <= height + width - 2 { - for x in 0..(step + 1) { - let y = step - x; - if x >= height || y >= width || obstacle_grid[x][y] == 1 { - continue; - } - if y >= 1 { - paths[x][y] = paths[x][y] + paths[x][y - 1]; - } - if x >= 1 { - paths[x][y] = paths[x][y] + paths[x - 1][y]; - } - } - step += 1; - } - paths[height - 1][width - 1] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_63() { - assert_eq!(Solution::unique_paths_with_obstacles(vec![vec![0]]), 1); - assert_eq!( - Solution::unique_paths_with_obstacles(vec![vec![0, 0], vec![0, 0],]), - 2 - ); - assert_eq!( - Solution::unique_paths_with_obstacles(vec![vec![0, 1], vec![1, 0],]), - 0 - ); - assert_eq!( - Solution::unique_paths_with_obstacles(vec![ - vec![0, 0, 0], - vec![0, 1, 0], - vec![0, 0, 0], - ]), - 2 - ); - assert_eq!( - Solution::unique_paths_with_obstacles(vec![ - vec![0, 0, 0, 0], - vec![0, 0, 0, 0], - vec![0, 0, 0, 0], - ]), - 10 - ); - assert_eq!( - Solution::unique_paths_with_obstacles(vec![ - vec![0, 0, 0, 0], - vec![0, 0, 0, 1], - vec![0, 0, 1, 0], - ]), - 0 - ); - } -} diff --git a/src/solution/s0064_minimum_path_sum.rs b/src/solution/s0064_minimum_path_sum.rs deleted file mode 100644 index d6340d50..00000000 --- a/src/solution/s0064_minimum_path_sum.rs +++ /dev/null @@ -1,69 +0,0 @@ -/** - * [64] Minimum Path Sum - * - * 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. - * - * Note: You can only move either down or right at any point in time. - * - * Example: - * - * - * Input: - * [ - * [1,3,1], - * [1,5,1], - * [4,2,1] - * ] - * Output: 7 - * Explanation: Because the path 1→3→1→1→1 minimizes the sum. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/minimum-path-sum/ -// discuss: https://leetcode.com/problems/minimum-path-sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn min_path_sum(grid: Vec>) -> i32 { - let (height, width) = (grid.len(), grid[0].len()); - let mut grid = grid; - let mut step = 1; - while step <= height + width - 2 { - for x in 0..(step + 1) { - let y = step - x; - if x >= height || y >= width { - continue; - } - if x < 1 { - grid[x][y] += grid[x][y - 1]; - } else if y < 1 { - grid[x][y] += grid[x - 1][y]; - } else { - grid[x][y] += i32::min(grid[x][y - 1], grid[x - 1][y]); - } - } - step += 1; - } - grid[height - 1][width - 1] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_64() { - assert_eq!(Solution::min_path_sum(vec![vec![2]]), 2); - assert_eq!( - Solution::min_path_sum(vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1],]), - 7 - ); - assert_eq!(Solution::min_path_sum(vec![vec![1, 3, 1],]), 5); - } -} diff --git a/src/solution/s0065_valid_number.rs b/src/solution/s0065_valid_number.rs deleted file mode 100644 index 11c5753d..00000000 --- a/src/solution/s0065_valid_number.rs +++ /dev/null @@ -1,60 +0,0 @@ -/** - * [65] Valid Number - * - * Validate if a given string can be interpreted as a decimal number. - * - * Some examples:
- * "0" => true
- * " 0.1 " => true
- * "abc" => false
- * "1 a" => false
- * "2e10" => true
- * " -90e3 " => true
- * " 1e" => false
- * "e3" => false
- * " 6e-1" => true
- * " 99e2.5 " => false
- * "53.5e93" => true
- * " --6 " => false
- * "-+3" => false
- * "95a54e53" => false - * - * 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: - * - * - * Numbers 0-9 - * Exponent - "e" - * Positive/negative sign - "+"/"-" - * Decimal point - "." - * - * - * Of course, the context of these characters also matters in the input. - * - * Update (2015-02-10):
- * 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. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/valid-number/ -// discuss: https://leetcode.com/problems/valid-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// hope that regex was included in std library... -// TODO: NFA -impl Solution { - pub fn is_number(s: String) -> bool { - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_65() {} -} diff --git a/src/solution/s0066_plus_one.rs b/src/solution/s0066_plus_one.rs deleted file mode 100644 index fb1ea045..00000000 --- a/src/solution/s0066_plus_one.rs +++ /dev/null @@ -1,72 +0,0 @@ -/** - * [66] Plus One - * - * Given a non-empty array of digits representing a non-negative integer, plus one to the integer. - * - * 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. - * - * You may assume the integer does not contain any leading zero, except the number 0 itself. - * - * Example 1: - * - * - * Input: [1,2,3] - * Output: [1,2,4] - * Explanation: The array represents the integer 123. - * - * - * Example 2: - * - * - * Input: [4,3,2,1] - * Output: [4,3,2,2] - * Explanation: The array represents the integer 4321. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/plus-one/ -// discuss: https://leetcode.com/problems/plus-one/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn plus_one(digits: Vec) -> Vec { - let mut digits = digits; - let mut carry = 0; - for i in (0..digits.len()).rev() { - digits[i] = if digits[i] == 9 { - carry = 1; - 0 - } else { - carry = 0; - digits[i] + 1 - }; - if carry == 0 { - break; - } - } - if carry > 0 { - digits.insert(0, 1); - } - digits - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_66() { - assert_eq!(Solution::plus_one(vec![0]), vec![1]); - assert_eq!(Solution::plus_one(vec![9, 9, 9, 9]), vec![1, 0, 0, 0, 0]); - assert_eq!( - Solution::plus_one(vec![1, 0, 9, 9, 9, 9]), - vec![1, 1, 0, 0, 0, 0] - ); - } -} diff --git a/src/solution/s0067_add_binary.rs b/src/solution/s0067_add_binary.rs deleted file mode 100644 index 8c9951cc..00000000 --- a/src/solution/s0067_add_binary.rs +++ /dev/null @@ -1,79 +0,0 @@ -/** - * [67] Add Binary - * - * Given two binary strings, return their sum (also a binary string). - * - * The input strings are both non-empty and contains only characters 1 or 0. - * - * Example 1: - * - * - * Input: a = "11", b = "1" - * Output: "100" - * - * Example 2: - * - * - * Input: a = "1010", b = "1011" - * Output: "10101" - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/add-binary/ -// discuss: https://leetcode.com/problems/add-binary/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::char::from_digit; -impl Solution { - pub fn add_binary(a: String, b: String) -> String { - let mut buf = Vec::with_capacity(usize::max(a.len(), b.len()) + 1); - let mut a: Vec = a.chars().collect(); - let mut b: Vec = b.chars().collect(); - let mut carry = 0; - while !(a.is_empty() && b.is_empty()) { - let mut sum = a.pop().map_or(0, |ch| ch.to_digit(10).unwrap()) - + b.pop().map_or(0, |ch| ch.to_digit(10).unwrap()) - + carry; - if sum > 1 { - sum -= 2; - carry = 1; - } else { - carry = 0; - } - buf.push(from_digit(sum, 10).unwrap()) - } - if carry > 0 { - buf.push('1') - } - buf.into_iter().rev().collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_67() { - assert_eq!( - Solution::add_binary("0".to_owned(), "0".to_owned()), - "0".to_owned() - ); - assert_eq!( - Solution::add_binary("1010".to_owned(), "1011".to_owned()), - "10101".to_owned() - ); - assert_eq!( - Solution::add_binary("11".to_owned(), "1".to_owned()), - "100".to_owned() - ); - assert_eq!( - Solution::add_binary("1111".to_owned(), "1111".to_owned()), - "11110".to_owned() - ); - } -} diff --git a/src/solution/s0068_text_justification.rs b/src/solution/s0068_text_justification.rs deleted file mode 100644 index 827fa4f8..00000000 --- a/src/solution/s0068_text_justification.rs +++ /dev/null @@ -1,200 +0,0 @@ -/** - * [68] Text Justification - * - * Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. - * - * You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. - * - * Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. - * - * For the last line of text, it should be left justified and no extra space is inserted between words. - * - * Note: - * - * - * A word is defined as a character sequence consisting of non-space characters only. - * Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. - * The input array words contains at least one word. - * - * - * Example 1: - * - * - * Input: - * words = ["This", "is", "an", "example", "of", "text", "justification."] - * maxWidth = 16 - * Output: - * [ - * "This is an", - * "example of text", - * "justification. " - * ] - * - * - * Example 2: - * - * - * Input: - * words = ["What","must","be","acknowledgment","shall","be"] - * maxWidth = 16 - * Output: - * [ - * "What must be", - * "acknowledgment ", - * "shall be " - * ] - * Explanation: Note that the last line is "shall be " instead of "shall be", - * because the last line must be left-justified instead of fully-justified. - * Note that the second line is also left-justified becase it contains only one word. - * - * - * Example 3: - * - * - * Input: - * words = ["Science","is","what","we","understand","well","enough","to","explain", - * "to","a","computer.","Art","is","everything","else","we","do"] - * maxWidth = 20 - * Output: - * [ - * "Science is what we", - * "understand well", - * "enough to explain to", - * "a computer. Art is", - * "everything else we", - * "do " - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/text-justification/ -// discuss: https://leetcode.com/problems/text-justification/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn full_justify(words: Vec, max_width: i32) -> Vec { - let mut res = Vec::new(); - let max_width = max_width as usize; - let mut i = 0; - let mut row_len = 0; - let mut buf = Vec::new(); - while i < words.len() { - if words[i].len() > max_width { - unreachable!() - } - let old_len = row_len; - row_len += words[i].len() + if row_len > 0 { 1 } else { 0 }; - if row_len > max_width { - res.push(Solution::compact(buf, max_width, old_len)); - buf = Vec::new(); - row_len = 0; - } else { - buf.push(words[i].clone()); - i += 1; - } - } - res.push(Solution::compact_last(buf, max_width)); - res - } - - fn compact(words: Vec, max_width: usize, row_len: usize) -> String { - let spaces = max_width - (row_len - words.len() + 1); - let avg_spaces = spaces / usize::max(1, words.len() - 1); - let mut extra_spaces = spaces - avg_spaces * usize::max(1, words.len() - 1);; - let mut res = String::new(); - for (i, word) in words.iter().enumerate() { - res.push_str(word); - if words.len() < 2 || (i < words.len() - 1) { - res.push_str(&" ".repeat(avg_spaces)); - if extra_spaces > 0 { - res.push(' '); - extra_spaces -= 1; - } - } - } - res - } - - fn compact_last(words: Vec, max_width: usize) -> String { - let mut res = String::new(); - for (i, word) in words.iter().enumerate() { - res.push_str(word); - if i < words.len() - 1 { - res.push(' '); - } - } - res.push_str(&" ".repeat(max_width - res.len())); - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_68() { - assert_eq!( - Solution::full_justify( - vec_string![ - "This", - "is", - "an", - "example", - "of", - "text", - "justification." - ], - 16 - ), - vec_string!["This is an", "example of text", "justification. "] - ); - - assert_eq!( - Solution::full_justify( - vec_string!["What", "must", "be", "acknowledgment", "shall", "be"], - 16 - ), - vec_string!["What must be", "acknowledgment ", "shall be "] - ); - - assert_eq!( - Solution::full_justify( - vec_string![ - "Science", - "is", - "what", - "we", - "understand", - "well", - "enough", - "to", - "explain", - "to", - "a", - "computer.", - "Art", - "is", - "everything", - "else", - "we", - "do" - ], - 20 - ), - vec_string![ - "Science is what we", - "understand well", - "enough to explain to", - "a computer. Art is", - "everything else we", - "do ", - ] - ); - } -} diff --git a/src/solution/s0069_sqrtx.rs b/src/solution/s0069_sqrtx.rs deleted file mode 100644 index 256f88be..00000000 --- a/src/solution/s0069_sqrtx.rs +++ /dev/null @@ -1,72 +0,0 @@ -/** - * [69] Sqrt(x) - * - * Implement int sqrt(int x). - * - * Compute and return the square root of x, where x is guaranteed to be a non-negative integer. - * - * Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. - * - * Example 1: - * - * - * Input: 4 - * Output: 2 - * - * - * Example 2: - * - * - * Input: 8 - * Output: 2 - * Explanation: The square root of 8 is 2.82842..., and since - * the decimal part is truncated, 2 is returned. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/sqrtx/ -// discuss: https://leetcode.com/problems/sqrtx/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Newton-Raphson for: root^2 - n = 0 -// Tangent equation: y = 2 * root * x - (root^2 + n) -// Zero point: (root^2 + n) / (2 * root) -impl Solution { - pub fn my_sqrt(x: i32) -> i32 { - let mut size = x; - let mut base = 1; - while size > 1 { - let half = size / 2; - let mid = base + half; - if mid <= x / mid { - base = mid; - } - size -= half; - } - base - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_69() { - assert_eq!(Solution::my_sqrt(8), 2); - assert_eq!(Solution::my_sqrt(16), 4); - assert_eq!(Solution::my_sqrt(17), 4); - assert_eq!(Solution::my_sqrt(81), 9); - assert_eq!(Solution::my_sqrt(82), 9); - assert_eq!(Solution::my_sqrt(100480577), 10024); - assert_eq!(Solution::my_sqrt(100480575), 10023); - assert_eq!(Solution::my_sqrt(100480575), 10023); - assert_eq!(Solution::my_sqrt(80), 8); - assert_eq!(Solution::my_sqrt(2), 1); - } -} diff --git a/src/solution/s0070_climbing_stairs.rs b/src/solution/s0070_climbing_stairs.rs deleted file mode 100644 index 2ef4153b..00000000 --- a/src/solution/s0070_climbing_stairs.rs +++ /dev/null @@ -1,71 +0,0 @@ -/** - * [70] Climbing Stairs - * - * You are climbing a stair case. It takes n steps to reach to the top. - * - * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? - * - * Note: Given n will be a positive integer. - * - * Example 1: - * - * - * Input: 2 - * Output: 2 - * Explanation: There are two ways to climb to the top. - * 1. 1 step + 1 step - * 2. 2 steps - * - * - * Example 2: - * - * - * Input: 3 - * Output: 3 - * Explanation: There are three ways to climb to the top. - * 1. 1 step + 1 step + 1 step - * 2. 1 step + 2 steps - * 3. 2 steps + 1 step - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/climbing-stairs/ -// discuss: https://leetcode.com/problems/climbing-stairs/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Bottom-up DP -impl Solution { - pub fn climb_stairs(n: i32) -> i32 { - let n = n as usize; - if n == 1 { - return 1; - } - if n == 2 { - return 2; - } - let (mut prev, mut curr) = (1, 2); - for i in 2..n { - let next = prev + curr; - prev = curr; - curr = next; - } - curr - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_70() { - assert_eq!(Solution::climb_stairs(3), 3); - assert_eq!(Solution::climb_stairs(4), 5); - assert_eq!(Solution::climb_stairs(5), 8); - } -} diff --git a/src/solution/s0071_simplify_path.rs b/src/solution/s0071_simplify_path.rs deleted file mode 100644 index 4b61f7be..00000000 --- a/src/solution/s0071_simplify_path.rs +++ /dev/null @@ -1,112 +0,0 @@ -/** - * [71] Simplify Path - * - * Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path. - * - * In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix - * - * Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path. - * - * - * - * Example 1: - * - * - * Input: "/home/" - * Output: "/home" - * Explanation: Note that there is no trailing slash after the last directory name. - * - * - * Example 2: - * - * - * Input: "/../" - * Output: "/" - * Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go. - * - * - * Example 3: - * - * - * Input: "/home//foo/" - * Output: "/home/foo" - * Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one. - * - * - * Example 4: - * - * - * Input: "/a/./b/../../c/" - * Output: "/c" - * - * - * Example 5: - * - * - * Input: "/a/../../b/../c//.//" - * Output: "/c" - * - * - * Example 6: - * - * - * Input: "/a//b////c/d//././/.." - * Output: "/a/b/c" - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/simplify-path/ -// discuss: https://leetcode.com/problems/simplify-path/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn simplify_path(path: String) -> String { - let mut stack = Vec::new(); - for s in path.split('/') { - match s { - "." => {} - "/" => {} - "" => {} - ".." => { - stack.pop(); - } - _ => stack.push(s), - } - } - let mut res = String::new(); - for s in stack { - res.push('/'); - res.push_str(s); - } - if res.len() > 0 { - res - } else { - "/".to_owned() - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_71() { - assert_eq!(Solution::simplify_path("/home/".to_owned()), "/home"); - assert_eq!(Solution::simplify_path("/../".to_owned()), "/"); - assert_eq!(Solution::simplify_path("/a/./b/../../c/".to_owned()), "/c"); - assert_eq!( - Solution::simplify_path("/a/../../b/../c//.//".to_owned()), - "/c" - ); - assert_eq!( - Solution::simplify_path("/a//b////c/d//././/..".to_owned()), - "/a/b/c" - ); - } -} diff --git a/src/solution/s0072_edit_distance.rs b/src/solution/s0072_edit_distance.rs deleted file mode 100644 index d50d9fa3..00000000 --- a/src/solution/s0072_edit_distance.rs +++ /dev/null @@ -1,60 +0,0 @@ -/** - * [72] Edit Distance - * - * Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. - * - * You have the following 3 operations permitted on a word: - * - *
    - * Insert a character - * Delete a character - * Replace a character - *
- * - * Example 1: - * - * - * Input: word1 = "horse", word2 = "ros" - * Output: 3 - * Explanation: - * horse -> rorse (replace 'h' with 'r') - * rorse -> rose (remove 'r') - * rose -> ros (remove 'e') - * - * - * Example 2: - * - * - * Input: word1 = "intention", word2 = "execution" - * Output: 5 - * Explanation: - * intention -> inention (remove 't') - * inention -> enention (replace 'i' with 'e') - * enention -> exention (replace 'n' with 'x') - * exention -> exection (replace 'n' with 'c') - * exection -> execution (insert 'u') - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/edit-distance/ -// discuss: https://leetcode.com/problems/edit-distance/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn min_distance(word1: String, word2: String) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_72() {} -} diff --git a/src/solution/s0073_set_matrix_zeroes.rs b/src/solution/s0073_set_matrix_zeroes.rs deleted file mode 100644 index 8d8cdab8..00000000 --- a/src/solution/s0073_set_matrix_zeroes.rs +++ /dev/null @@ -1,68 +0,0 @@ -/** - * [73] Set Matrix Zeroes - * - * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. - * - * Example 1: - * - * - * Input: - * [ - * [1,1,1], - * [1,0,1], - * [1,1,1] - * ] - * Output: - * [ - * [1,0,1], - * [0,0,0], - * [1,0,1] - * ] - * - * - * Example 2: - * - * - * Input: - * [ - * [0,1,2,0], - * [3,4,5,2], - * [1,3,1,5] - * ] - * Output: - * [ - * [0,0,0,0], - * [0,4,5,0], - * [0,3,1,0] - * ] - * - * - * Follow up: - * - * - * A straight forward solution using O(mn) space is probably a bad idea. - * A simple improvement uses O(m + n) space, but still not the best solution. - * Could you devise a constant space solution? - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/set-matrix-zeroes/ -// discuss: https://leetcode.com/problems/set-matrix-zeroes/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn set_zeroes(matrix: &mut Vec>) {} -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_73() {} -} diff --git a/src/solution/s0074_search_a_2d_matrix.rs b/src/solution/s0074_search_a_2d_matrix.rs deleted file mode 100644 index 90975918..00000000 --- a/src/solution/s0074_search_a_2d_matrix.rs +++ /dev/null @@ -1,92 +0,0 @@ -/** - * [74] Search a 2D Matrix - * - * Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: - * - * - * Integers in each row are sorted from left to right. - * The first integer of each row is greater than the last integer of the previous row. - * - * - * Example 1: - * - * - * Input: - * matrix = [ - * [1, 3, 5, 7], - * [10, 11, 16, 20], - * [23, 30, 34, 50] - * ] - * target = 3 - * Output: true - * - * - * Example 2: - * - * - * Input: - * matrix = [ - * [1, 3, 5, 7], - * [10, 11, 16, 20], - * [23, 30, 34, 50] - * ] - * target = 13 - * Output: false - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/search-a-2d-matrix/ -// discuss: https://leetcode.com/problems/search-a-2d-matrix/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn search_matrix(matrix: Vec>, target: i32) -> bool { - if matrix.is_empty() { - return false; - } - let (height, width) = (matrix.len(), matrix[0].len()); - if height < 1 || width < 1 { - return false; - } - let mut size = height * width; - let mut base = 0_usize; - while size > 1 { - let half = size / 2; - let mid = base + half; - if target == matrix[mid / width][mid % width] { - return true; - } else if (target > matrix[mid / width][mid % width]) { - base = mid; - } - size -= half; - } - target == matrix[base / width][base % width] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_74() { - assert_eq!( - Solution::search_matrix( - vec![vec![1, 3, 5, 7], vec![10, 11, 16, 20], vec![23, 30, 34, 50]], - 3 - ), - true - ); - assert_eq!( - Solution::search_matrix( - vec![vec![1, 3, 5, 7], vec![10, 11, 16, 20], vec![23, 30, 34, 50]], - 13 - ), - false - ); - } -} diff --git a/src/solution/s0075_sort_colors.rs b/src/solution/s0075_sort_colors.rs deleted file mode 100644 index 6b72ac88..00000000 --- a/src/solution/s0075_sort_colors.rs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * [75] Sort Colors - * - * Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. - * - * Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. - * - * Note: You are not suppose to use the library's sort function for this problem. - * - * Example: - * - * - * Input: [2,0,2,1,1,0] - * Output: [0,0,1,1,2,2] - * - * Follow up: - * - * - * A rather straight forward solution is a two-pass algorithm using counting sort.
- * First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. - * Could you come up with a one-pass algorithm using only constant space? - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/sort-colors/ -// discuss: https://leetcode.com/problems/sort-colors/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// three-way partition -impl Solution { - pub fn sort_colors(nums: &mut Vec) { - if nums.is_empty() { - return; - } - let (mut lower_idx, mut upper_idx) = (0_usize, nums.len() - 1); - let mut i = 0_usize; - while i <= upper_idx { - if nums[i] < 1 { - // lower_idx <= i, we've scanned it so we know nums[lower_idx] <= 1, i++ - nums.swap(lower_idx, i); - i += 1; - lower_idx += 1; - } else if nums[i] > 1 { - nums.swap(upper_idx, i); - if upper_idx < 1 { - break; - } - upper_idx -= 1; - } else { - i += 1; - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_75() { - let mut vec = vec![ - 1, 2, 0, 1, 2, 2, 2, 0, 0, 0, 2, 1, 1, 2, 0, 1, 2, 2, 1, 1, 0, - ]; - Solution::sort_colors(&mut vec); - assert_eq!( - vec, - vec![0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2] - ); - - let mut vec = vec![]; - Solution::sort_colors(&mut vec); - assert_eq!(vec, vec![]); - - let mut vec = vec![2, 2, 2]; - Solution::sort_colors(&mut vec); - assert_eq!(vec, vec![2, 2, 2]); - } -} diff --git a/src/solution/s0076_minimum_window_substring.rs b/src/solution/s0076_minimum_window_substring.rs deleted file mode 100644 index 9d190533..00000000 --- a/src/solution/s0076_minimum_window_substring.rs +++ /dev/null @@ -1,56 +0,0 @@ -/** - * [76] Minimum Window Substring - * - * 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). - * - * Example: - * - * - * Input: S = "ADOBECODEBANC", T = "ABC" - * Output: "BANC" - * - * - * Note: - * - * - * If there is no such window in S that covers all characters in T, return the empty string "". - * If there is such window, you are guaranteed that there will always be only one unique minimum window in S. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/minimum-window-substring/ -// discuss: https://leetcode.com/problems/minimum-window-substring/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -use std::collections::HashMap; -impl Solution { - pub fn min_window(s: String, t: String) -> String { - if t.is_empty() || t.len() > s.len() { - return "".to_owned(); - } - let (mut start, mut end) = (0_usize, 0_usize); - let mut result = (0_usize, 0_usize); - loop {} - s[result.0..result.1].to_owned() - } - - fn count_char(s: String) -> HashMap { - let mut res = HashMap::new(); - for ch in s.chars().into_iter() { - *res.entry(ch).or_insert(0) += 1; - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_76() {} -} diff --git a/src/solution/s0077_combinations.rs b/src/solution/s0077_combinations.rs deleted file mode 100644 index 6bb10d6b..00000000 --- a/src/solution/s0077_combinations.rs +++ /dev/null @@ -1,77 +0,0 @@ -/** - * [77] Combinations - * - * Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. - * - * Example: - * - * - * Input: n = 4, k = 2 - * Output: - * [ - * [2,4], - * [3,4], - * [2,3], - * [1,2], - * [1,3], - * [1,4], - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/combinations/ -// discuss: https://leetcode.com/problems/combinations/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn combine(n: i32, k: i32) -> Vec> { - let mut res: Vec> = Vec::new(); - Solution::backtrack(1, n, k, vec![], &mut res); - res - } - - fn backtrack(start: i32, end: i32, k: i32, curr: Vec, result: &mut Vec>) { - if k < 1 { - result.push(curr); - return; - } - if end - start + 1 < k { - // elements is not enough, return quickly - return; - } - for i in start..end + 1 { - let mut vec = curr.clone(); - vec.push(i); - Solution::backtrack(i + 1, end, k - 1, vec, result); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_77() { - assert_eq!( - Solution::combine(4, 2), - vec![ - vec![1, 2], - vec![1, 3], - vec![1, 4], - vec![2, 3], - vec![2, 4], - vec![3, 4] - ] - ); - assert_eq!(Solution::combine(1, 1), vec![vec![1]]); - let empty: Vec> = vec![]; - assert_eq!(Solution::combine(0, 1), empty); - assert_eq!(Solution::combine(2, 1), vec![vec![1], vec![2]]); - } -} diff --git a/src/solution/s0078_subsets.rs b/src/solution/s0078_subsets.rs deleted file mode 100644 index 2db34925..00000000 --- a/src/solution/s0078_subsets.rs +++ /dev/null @@ -1,67 +0,0 @@ -/** - * [78] Subsets - * - * Given a set of distinct integers, nums, return all possible subsets (the power set). - * - * Note: The solution set must not contain duplicate subsets. - * - * Example: - * - * - * Input: nums = [1,2,3] - * Output: - * [ - * [3], - * [1], - * [2], - * [1,2,3], - * [1,3], - * [2,3], - * [1,2], - * [] - * ] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/subsets/ -// discuss: https://leetcode.com/problems/subsets/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn subsets(nums: Vec) -> Vec> { - let mut res = Vec::new(); - Solution::backtrack(0, vec![], &nums, &mut res); - res - } - - fn backtrack(start: usize, mut curr: Vec, nums: &Vec, result: &mut Vec>) { - if start >= nums.len() { - result.push(curr); - return; - } - // current element dropped - Solution::backtrack(start + 1, curr.clone(), nums, result); - // current element picked - curr.push(nums[start]); - Solution::backtrack(start + 1, curr, nums, result); - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_78() { - assert_eq!(Solution::subsets(vec![]), vec![vec![]]); - assert_eq!(Solution::subsets(vec![1]), vec![vec![], vec![1]]); - assert_eq!( - Solution::subsets(vec![1, 2]), - vec![vec![], vec![2], vec![1], vec![1, 2]] - ); - } -} diff --git a/src/solution/s0079_word_search.rs b/src/solution/s0079_word_search.rs deleted file mode 100644 index 07c4a705..00000000 --- a/src/solution/s0079_word_search.rs +++ /dev/null @@ -1,133 +0,0 @@ -/** - * [79] Word Search - * - * Given a 2D board and a word, find if the word exists in the grid. - * - * The word can 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. - * - * Example: - * - * - * board = - * [ - * ['A','B','C','E'], - * ['S','F','C','S'], - * ['A','D','E','E'] - * ] - * - * Given word = "ABCCED", return true. - * Given word = "SEE", return true. - * Given word = "ABCB", return false. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/word-search/ -// discuss: https://leetcode.com/problems/word-search/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO: use HashSet to record visited pos -impl Solution { - pub fn exist(board: Vec>, word: String) -> bool { - if board.is_empty() || word.len() < 1 { - return false; - } - let (height, width) = (board.len(), board[0].len()); - if height < 1 || width < 1 { - return false; - } - let seq: Vec = word.chars().collect(); - - for i in 0..height * width { - if Solution::dfs( - i / width, - i % width, - &seq[..], - &board, - vec![], - height, - width, - ) { - return true; - } - } - false - } - - fn dfs( - x: usize, - y: usize, - seq: &[char], - board: &Vec>, - mut visited: Vec<(usize, usize)>, - height: usize, - width: usize, - ) -> bool { - if seq[0] != board[x][y] { - return false; - } - if seq.len() < 2 { - return true; - } - visited.push((x, y)); - return (x > 0 - && !visited.contains(&(x - 1, y)) - && Solution::dfs(x - 1, y, &seq[1..], board, visited.clone(), height, width)) - || (x + 1 < height - && !visited.contains(&(x + 1, y)) - && Solution::dfs(x + 1, y, &seq[1..], board, visited.clone(), height, width)) - || (y > 0 - && !visited.contains(&(x, y - 1)) - && Solution::dfs(x, y - 1, &seq[1..], board, visited.clone(), height, width)) - || (y + 1 < width - && !visited.contains(&(x, y + 1)) - && Solution::dfs(x, y + 1, &seq[1..], board, visited.clone(), height, width)); - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_79() { - assert_eq!(Solution::exist(vec![vec!['a']], "a".to_owned()), true); - assert_eq!( - Solution::exist( - vec![ - vec!['A', 'B', 'C', 'E'], - vec!['S', 'F', 'C', 'S'], - vec!['A', 'D', 'E', 'E'], - ], - "ABCCED".to_owned() - ), - true - ); - assert_eq!( - Solution::exist( - vec![ - vec!['A', 'B', 'C', 'E'], - vec!['S', 'F', 'C', 'S'], - vec!['A', 'D', 'E', 'E'], - ], - "SEE".to_owned() - ), - true - ); - assert_eq!( - Solution::exist( - vec![ - vec!['A', 'B', 'C', 'E'], - vec!['S', 'F', 'C', 'S'], - vec!['A', 'D', 'E', 'E'], - ], - "ABCB".to_owned() - ), - false - ); - } -} diff --git a/src/solution/s0080_remove_duplicates_from_sorted_array_ii.rs b/src/solution/s0080_remove_duplicates_from_sorted_array_ii.rs deleted file mode 100644 index 70b3cf82..00000000 --- a/src/solution/s0080_remove_duplicates_from_sorted_array_ii.rs +++ /dev/null @@ -1,68 +0,0 @@ -/** - * [80] Remove Duplicates from Sorted Array II - * - * Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length. - * - * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. - * - * Example 1: - * - * - * Given nums = [1,1,1,2,2,3], - * - * Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. - * - * It doesn't matter what you leave beyond the returned length. - * - * Example 2: - * - * - * Given nums = [0,0,1,1,1,1,2,3,3], - * - * Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively. - * - * It doesn't matter what values are set beyond the returned length. - * - * - * Clarification: - * - * Confused why the returned value is an integer but your answer is an array? - * - * Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. - * - * Internally you can think of this: - * - * - * // nums is passed in by reference. (i.e., without making a copy) - * int len = removeDuplicates(nums); - * - * // any modification to nums in your function would be known by the caller. - * // using the length returned by your function, it prints the first len elements. - * for (int i = 0; i < len; i++) { - * print(nums[i]); - * } - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ -// discuss: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn remove_duplicates(nums: &mut Vec) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_80() {} -} diff --git a/src/solution/s0081_search_in_rotated_sorted_array_ii.rs b/src/solution/s0081_search_in_rotated_sorted_array_ii.rs deleted file mode 100644 index 7972a16f..00000000 --- a/src/solution/s0081_search_in_rotated_sorted_array_ii.rs +++ /dev/null @@ -1,52 +0,0 @@ -/** - * [81] Search in Rotated Sorted Array II - * - * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. - * - * (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). - * - * You are given a target value to search. If found in the array return true, otherwise return false. - * - * Example 1: - * - * - * Input: nums = [2,5,6,0,0,1,2], target = 0 - * Output: true - * - * - * Example 2: - * - * - * Input: nums = [2,5,6,0,0,1,2], target = 3 - * Output: false - * - * Follow up: - * - * - * This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates. - * Would this affect the run-time complexity? How and why? - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/search-in-rotated-sorted-array-ii/ -// discuss: https://leetcode.com/problems/search-in-rotated-sorted-array-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn search(nums: Vec, target: i32) -> bool { - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_81() {} -} diff --git a/src/solution/s0082_remove_duplicates_from_sorted_list_ii.rs b/src/solution/s0082_remove_duplicates_from_sorted_list_ii.rs deleted file mode 100644 index 067d0c79..00000000 --- a/src/solution/s0082_remove_duplicates_from_sorted_list_ii.rs +++ /dev/null @@ -1,59 +0,0 @@ -/** - * [82] Remove Duplicates from Sorted List II - * - * Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. - * - * Example 1: - * - * - * Input: 1->2->3->3->4->4->5 - * Output: 1->2->5 - * - * - * Example 2: - * - * - * Input: 1->1->1->2->3 - * Output: 2->3 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ -// discuss: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn delete_duplicates(head: Option>) -> Option> { - None - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_82() {} -} diff --git a/src/solution/s0083_remove_duplicates_from_sorted_list.rs b/src/solution/s0083_remove_duplicates_from_sorted_list.rs deleted file mode 100644 index 5c9552cc..00000000 --- a/src/solution/s0083_remove_duplicates_from_sorted_list.rs +++ /dev/null @@ -1,59 +0,0 @@ -/** - * [83] Remove Duplicates from Sorted List - * - * Given a sorted linked list, delete all duplicates such that each element appear only once. - * - * Example 1: - * - * - * Input: 1->1->2 - * Output: 1->2 - * - * - * Example 2: - * - * - * Input: 1->1->2->3->3 - * Output: 1->2->3 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/remove-duplicates-from-sorted-list/ -// discuss: https://leetcode.com/problems/remove-duplicates-from-sorted-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn delete_duplicates(head: Option>) -> Option> { - None - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_83() {} -} diff --git a/src/solution/s0084_largest_rectangle_in_histogram.rs b/src/solution/s0084_largest_rectangle_in_histogram.rs deleted file mode 100644 index d33b9bda..00000000 --- a/src/solution/s0084_largest_rectangle_in_histogram.rs +++ /dev/null @@ -1,91 +0,0 @@ -/** - * [84] Largest Rectangle in Histogram - * - * Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. - * - * - * - *
- * Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. - * - * - * - *
- * The largest rectangle is shown in the shaded area, which has area = 10 unit. - * - * - * - * Example: - * - * - * Input: [2,1,5,6,2,3] - * Output: 10 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/largest-rectangle-in-histogram/ -// discuss: https://leetcode.com/problems/largest-rectangle-in-histogram/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// record the height and start position using 2 stack, thus we reuse the previously scanned information -impl Solution { - pub fn largest_rectangle_area(heights: Vec) -> i32 { - let mut positions = Vec::new(); - let mut hs = Vec::new(); - let mut max_area = 0; - let len = heights.len(); - for (i, h) in heights.into_iter().enumerate() { - let mut last_pop = None; - while hs.last().is_some() && *hs.last().unwrap() >= h { - max_area = i32::max( - max_area, - hs.last().unwrap() * ((i - positions.last().unwrap()) as i32), - ); - hs.pop(); - last_pop = positions.pop(); - } - if last_pop.is_some() { - positions.push(last_pop.unwrap()); - } else { - positions.push(i); - } - hs.push(h); - } - // drain stack - while !hs.is_empty() { - max_area = i32::max( - max_area, - hs.last().unwrap() * ((len - positions.last().unwrap()) as i32), - ); - positions.pop(); - hs.pop(); - } - max_area - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_84() { - assert_eq!(Solution::largest_rectangle_area(vec![2, 1, 5, 6, 2, 3]), 10); - assert_eq!( - Solution::largest_rectangle_area(vec![1, 1, 1, 1, 1, 1, 1, 1]), - 8 - ); - assert_eq!(Solution::largest_rectangle_area(vec![2, 2]), 4); - assert_eq!( - Solution::largest_rectangle_area(vec![1, 2, 8, 8, 2, 2, 1]), - 16 - ); - assert_eq!(Solution::largest_rectangle_area(vec![2, 1, 2]), 3); - assert_eq!(Solution::largest_rectangle_area(vec![1, 3, 2, 1, 2]), 5); - } -} diff --git a/src/solution/s0085_maximal_rectangle.rs b/src/solution/s0085_maximal_rectangle.rs deleted file mode 100644 index 6dbf2951..00000000 --- a/src/solution/s0085_maximal_rectangle.rs +++ /dev/null @@ -1,43 +0,0 @@ -/** - * [85] Maximal Rectangle - * - * Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area. - * - * Example: - * - * - * Input: - * [ - * ["1","0","1","0","0"], - * ["1","0","1","1","1"], - * ["1","1","1","1","1"], - * ["1","0","0","1","0"] - * ] - * Output: 6 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/maximal-rectangle/ -// discuss: https://leetcode.com/problems/maximal-rectangle/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn maximal_rectangle(matrix: Vec>) -> i32 { - let mut max_area = 0; - - max_area - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_85() {} -} diff --git a/src/solution/s0086_partition_list.rs b/src/solution/s0086_partition_list.rs deleted file mode 100644 index 1f4952dd..00000000 --- a/src/solution/s0086_partition_list.rs +++ /dev/null @@ -1,65 +0,0 @@ -/** - * [86] Partition List - * - * 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. - * - * You should preserve the original relative order of the nodes in each of the two partitions. - * - * Example: - * - * - * Input: head = 1->4->3->2->5->2, x = 3 - * Output: 1->2->2->4->3->5 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/partition-list/ -// discuss: https://leetcode.com/problems/partition-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn partition(head: Option>, x: i32) -> Option> { - let mut lower = Some(Box::new(ListNode::new(0))); - let mut higher = Some(Box::new(ListNode::new(0))); - let mut lower_tail = lower.as_mut(); - let mut higher_tail = higher.as_mut(); - let mut head = head; - while let Some(mut inner) = head { - let mut next = inner.next.take(); - if inner.val < x { - lower_tail.as_mut().unwrap().next = Some(inner); - lower_tail = lower_tail.unwrap().next.as_mut(); - } else { - higher_tail.as_mut().unwrap().next = Some(inner); - higher_tail = higher_tail.unwrap().next.as_mut(); - } - head = next - } - lower_tail.as_mut().unwrap().next = higher.unwrap().next.take(); - lower.unwrap().next.take() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_86() { - assert_eq!( - Solution::partition(linked![1, 4, 3, 2, 5, 2], 3), - linked![1, 2, 2, 4, 3, 5] - ); - assert_eq!( - Solution::partition(linked![1, 4, 3, 2, 5, 2], 8), - linked![1, 4, 3, 2, 5, 2] - ); - assert_eq!(Solution::partition(linked![], 0), linked![]); - } -} diff --git a/src/solution/s0087_scramble_string.rs b/src/solution/s0087_scramble_string.rs deleted file mode 100644 index 19b47dc0..00000000 --- a/src/solution/s0087_scramble_string.rs +++ /dev/null @@ -1,85 +0,0 @@ -/** - * [87] Scramble String - * - * Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. - * - * Below is one possible representation of s1 = "great": - * - * - * great - * / \ - * gr eat - * / \ / \ - * g r e at - * / \ - * a t - * - * - * To scramble the string, we may choose any non-leaf node and swap its two children. - * - * For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat". - * - * - * rgeat - * / \ - * rg eat - * / \ / \ - * r g e at - * / \ - * a t - * - * - * We say that "rgeat" is a scrambled string of "great". - * - * Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae". - * - * - * rgtae - * / \ - * rg tae - * / \ / \ - * r g ta e - * / \ - * t a - * - * - * We say that "rgtae" is a scrambled string of "great". - * - * Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1. - * - * Example 1: - * - * - * Input: s1 = "great", s2 = "rgeat" - * Output: true - * - * - * Example 2: - * - * - * Input: s1 = "abcde", s2 = "caebd" - * Output: false - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/scramble-string/ -// discuss: https://leetcode.com/problems/scramble-string/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn is_scramble(s1: String, s2: String) -> bool { - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_87() {} -} diff --git a/src/solution/s0088_merge_sorted_array.rs b/src/solution/s0088_merge_sorted_array.rs deleted file mode 100644 index bdcc2a1a..00000000 --- a/src/solution/s0088_merge_sorted_array.rs +++ /dev/null @@ -1,72 +0,0 @@ -/** - * [88] Merge Sorted Array - * - * Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. - * - * Note: - * - * - * The number of elements initialized in nums1 and nums2 are m and n respectively. - * You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. - * - * - * Example: - * - * - * Input: - * nums1 = [1,2,3,0,0,0], m = 3 - * nums2 = [2,5,6], n = 3 - * - * Output: [1,2,2,3,5,6] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/merge-sorted-array/ -// discuss: https://leetcode.com/problems/merge-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn merge(nums1: &mut Vec, m: i32, nums2: &mut Vec, n: i32) { - let mut i = m - 1; - let mut j = n - 1; - let mut z = m + n - 1; - while z >= 0 { - if i >= 0 && (j < 0 || nums1[i as usize] >= nums2[j as usize]) { - nums1[z as usize] = nums1[i as usize]; - i -= 1; - } else { - nums1[z as usize] = nums2[j as usize]; - j -= 1; - } - z -= 1; - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_88() { - let mut vec1 = vec![1, 2, 3, 0, 0, 0]; - let mut vec2 = vec![2, 5, 6]; - Solution::merge(&mut vec1, 3, &mut vec2, 3); - assert_eq!(vec1, vec![1, 2, 2, 3, 5, 6]); - - let mut vec1 = vec![1, 2, 3]; - let mut vec2 = vec![]; - Solution::merge(&mut vec1, 3, &mut vec2, 0); - assert_eq!(vec1, vec![1, 2, 3]); - - let mut vec1 = vec![0, 0, 0]; - let mut vec2 = vec![1, 2, 3]; - Solution::merge(&mut vec1, 0, &mut vec2, 3); - assert_eq!(vec1, vec![1, 2, 3]); - } -} diff --git a/src/solution/s0089_gray_code.rs b/src/solution/s0089_gray_code.rs deleted file mode 100644 index 039283eb..00000000 --- a/src/solution/s0089_gray_code.rs +++ /dev/null @@ -1,82 +0,0 @@ -/** - * [89] Gray Code - * - * The gray code is a binary numeral system where two successive values differ in only one bit. - * - * 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. - * - * Example 1: - * - * - * Input: 2 - * Output: [0,1,3,2] - * Explanation: - * 00 - 0 - * 01 - 1 - * 11 - 3 - * 10 - 2 - * - * For a given n, a gray code sequence may not be uniquely defined. - * For example, [0,2,3,1] is also a valid gray code sequence. - * - * 00 - 0 - * 10 - 2 - * 11 - 3 - * 01 - 1 - * - * - * Example 2: - * - * - * Input: 0 - * Output: [0] - * Explanation: We define the gray code sequence to begin with 0. - * A gray code sequence of n has size = 2^n, which for n = 0 the size is 2^0 = 1. - * Therefore, for n = 0 the gray code sequence is [0]. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/gray-code/ -// discuss: https://leetcode.com/problems/gray-code/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -0000 -0001 <- flip [0] to 1, traverse [] in reverse order -0011 <- flip [1] to 1, traverse [0] in reverse order -0010 -0110 <- flip [2] to 1, traverse [1,0] in reverse order -0111 -0101 -0100 -1100 <- flip [3] to 1, traverse [2,1,0] in reverse order - */ -impl Solution { - pub fn gray_code(n: i32) -> Vec { - let mut res = vec![0]; - for i in 0..n { - for j in (0..res.len()).rev() { - res.push(2_i32.pow(i as u32) + res[j]); - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_89() { - assert_eq!(Solution::gray_code(2), vec![0, 1, 3, 2]); - assert_eq!(Solution::gray_code(1), vec![0, 1]); - assert_eq!(Solution::gray_code(0), vec![0]); - assert_eq!(Solution::gray_code(3), vec![0, 1, 3, 2, 6, 7, 5, 4]); - } -} diff --git a/src/solution/s0090_subsets_ii.rs b/src/solution/s0090_subsets_ii.rs deleted file mode 100644 index e859e2d1..00000000 --- a/src/solution/s0090_subsets_ii.rs +++ /dev/null @@ -1,95 +0,0 @@ -/** - * [90] Subsets II - * - * Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). - * - * Note: The solution set must not contain duplicate subsets. - * - * Example: - * - * - * Input: [1,2,2] - * Output: - * [ - * [2], - * [1], - * [1,2,2], - * [2,2], - * [1,2], - * [] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/subsets-ii/ -// discuss: https://leetcode.com/problems/subsets-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -count the repeats of each number, -then in backtracking, each number can be picked up for 0..repeat times - -using BTreeMap to preserve order (easy for test) -*/ -use std::collections::BTreeMap; -impl Solution { - pub fn subsets_with_dup(nums: Vec) -> Vec> { - let mut res = Vec::new(); - let nums = nums - .into_iter() - .fold(BTreeMap::new(), |mut map, v| { - *map.entry(v).or_insert(0) += 1; - map - }) - .into_iter() - .collect::>(); - Solution::backtrack(0, vec![], &nums, &mut res); - res - } - - fn backtrack( - start: usize, - mut curr: Vec, - nums: &Vec<(i32, i32)>, - result: &mut Vec>, - ) { - if start >= nums.len() { - result.push(curr); - return; - } - for repeat in 0..nums[start].1 + 1 { - let mut inner = curr.clone(); - for _ in 0..repeat { - inner.push(nums[start].0); - } - Solution::backtrack(start + 1, inner, nums, result); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_90() { - assert_eq!( - Solution::subsets_with_dup(vec![1, 2, 2]), - vec![ - vec![], - vec![2], - vec![2, 2], - vec![1], - vec![1, 2], - vec![1, 2, 2], - ] - ); - assert_eq!(Solution::subsets_with_dup(vec![1]), vec![vec![], vec![1],]); - assert_eq!(Solution::subsets_with_dup(vec![]), vec![vec![],]); - } -} diff --git a/src/solution/s0091_decode_ways.rs b/src/solution/s0091_decode_ways.rs deleted file mode 100644 index bbecc932..00000000 --- a/src/solution/s0091_decode_ways.rs +++ /dev/null @@ -1,52 +0,0 @@ -/** - * [91] Decode Ways - * - * A message containing letters from A-Z is being encoded to numbers using the following mapping: - * - * - * 'A' -> 1 - * 'B' -> 2 - * ... - * 'Z' -> 26 - * - * - * Given a non-empty string containing only digits, determine the total number of ways to decode it. - * - * Example 1: - * - * - * Input: "12" - * Output: 2 - * Explanation: It could be decoded as "AB" (1 2) or "L" (12). - * - * - * Example 2: - * - * - * Input: "226" - * Output: 3 - * Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/decode-ways/ -// discuss: https://leetcode.com/problems/decode-ways/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn num_decodings(s: String) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_91() {} -} diff --git a/src/solution/s0092_reverse_linked_list_ii.rs b/src/solution/s0092_reverse_linked_list_ii.rs deleted file mode 100644 index 318c0d15..00000000 --- a/src/solution/s0092_reverse_linked_list_ii.rs +++ /dev/null @@ -1,54 +0,0 @@ -/** - * [92] Reverse Linked List II - * - * Reverse a linked list from position m to n. Do it in one-pass. - * - * Note: 1 ≤ m ≤ n ≤ length of list. - * - * Example: - * - * - * Input: 1->2->3->4->5->NULL, m = 2, n = 4 - * Output: 1->4->3->2->5->NULL - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/reverse-linked-list-ii/ -// discuss: https://leetcode.com/problems/reverse-linked-list-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for singly-linked list. -// #[derive(PartialEq, Eq, Debug)] -// pub struct ListNode { -// pub val: i32, -// pub next: Option> -// } -// -// impl ListNode { -// #[inline] -// fn new(val: i32) -> Self { -// ListNode { -// next: None, -// val -// } -// } -// } -impl Solution { - pub fn reverse_between(head: Option>, m: i32, n: i32) -> Option> { - None - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_92() {} -} diff --git a/src/solution/s0093_restore_ip_addresses.rs b/src/solution/s0093_restore_ip_addresses.rs deleted file mode 100644 index 5c2706b4..00000000 --- a/src/solution/s0093_restore_ip_addresses.rs +++ /dev/null @@ -1,35 +0,0 @@ -/** - * [93] Restore IP Addresses - * - * Given a string containing only digits, restore it by returning all possible valid IP address combinations. - * - * Example: - * - * - * Input: "25525511135" - * Output: ["255.255.11.135", "255.255.111.35"] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/restore-ip-addresses/ -// discuss: https://leetcode.com/problems/restore-ip-addresses/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn restore_ip_addresses(s: String) -> Vec { - vec![] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_93() {} -} diff --git a/src/solution/s0094_binary_tree_inorder_traversal.rs b/src/solution/s0094_binary_tree_inorder_traversal.rs deleted file mode 100644 index 01afb57a..00000000 --- a/src/solution/s0094_binary_tree_inorder_traversal.rs +++ /dev/null @@ -1,64 +0,0 @@ -/** - * [94] Binary Tree Inorder Traversal - * - * Given a binary tree, return the inorder traversal of its nodes' values. - * - * Example: - * - * - * Input: [1,null,2,3] - * 1 - * \ - * 2 - * / - * 3 - * - * Output: [1,3,2] - * - * Follow up: Recursive solution is trivial, could you do it iteratively? - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/binary-tree-inorder-traversal/ -// discuss: https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use crate::util::tree::{to_tree, TreeNode}; -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn inorder_traversal(root: Option>>) -> Vec { - let mut res = Vec::new(); - Solution::inorder_traverse(root.as_ref(), &mut (|v| res.push(v))); - res - } - - fn inorder_traverse(root: Option<&Rc>>, consumer: &mut F) { - if let Some(node) = root { - Solution::inorder_traverse(node.borrow().left.as_ref(), consumer); - consumer(root.as_ref().unwrap().borrow().val); - Solution::inorder_traverse(node.borrow().right.as_ref(), consumer); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_94() { - assert_eq!( - Solution::inorder_traversal(tree![1, null, 2, 3]), - vec![1, 3, 2] - ); - assert_eq!( - Solution::inorder_traversal(tree![1, 2, 3, 4, 5, 6, 7]), - vec![4, 2, 5, 1, 6, 3, 7] - ); - } -} diff --git a/src/solution/s0095_unique_binary_search_trees_ii.rs b/src/solution/s0095_unique_binary_search_trees_ii.rs deleted file mode 100644 index 1f75639d..00000000 --- a/src/solution/s0095_unique_binary_search_trees_ii.rs +++ /dev/null @@ -1,89 +0,0 @@ -/** - * [95] Unique Binary Search Trees II - * - * Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. - * - * Example: - * - * - * Input: 3 - * Output: - * [ - * [1,null,3,2], - * [3,2,null,1], - * [3,1,null,null,2], - * [2,1,3], - * [1,null,2,null,3] - * ] - * Explanation: - * The above output corresponds to the 5 unique BST's shown below: - * - * 1 3 3 2 1 - * \ / / / \ \ - * 3 2 1 1 3 2 - * / / \ \ - * 2 1 2 3 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/unique-binary-search-trees-ii/ -// discuss: https://leetcode.com/problems/unique-binary-search-trees-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* - 1 - - 1 2 - \ / - 2 1 - - 1 3 3 2 1 - \ / / / \ \ - 3 2 1 1 3 2 - / / \ \ - 2 1 2 3 - - 4 1 - / \ -(5*) 3 - / \ - 2 4 - */ -use crate::util::tree::{to_tree, TreeNode}; -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn generate_trees(n: i32) -> Vec>>> { - if n < 1 { - return vec![]; - } - let mut res = vec![Some(Rc::new(RefCell::new(TreeNode::new(1))))]; - for val in 2..n + 1 { - let mut next = Vec::new(); - for root in res.into_iter() { - let mut dummy = Some(Rc::new(RefCell::new(TreeNode { - val: 0, - left: None, - right: None, - }))); - let mut parent = dummy.as_ref().unwrap().clone(); - let mut node = root; - // we know that val is larger than all the elements in the tree - } - res = next; - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_95() {} -} diff --git a/src/solution/s0096_unique_binary_search_trees.rs b/src/solution/s0096_unique_binary_search_trees.rs deleted file mode 100644 index 4f64c26c..00000000 --- a/src/solution/s0096_unique_binary_search_trees.rs +++ /dev/null @@ -1,43 +0,0 @@ -/** - * [96] Unique Binary Search Trees - * - * Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? - * - * Example: - * - * - * Input: 3 - * Output: 5 - * Explanation: - * Given n = 3, there are a total of 5 unique BST's: - * - * 1 3 3 2 1 - * \ / / / \ \ - * 3 2 1 1 3 2 - * / / \ \ - * 2 1 2 3 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/unique-binary-search-trees/ -// discuss: https://leetcode.com/problems/unique-binary-search-trees/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn num_trees(n: i32) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_96() {} -} diff --git a/src/solution/s0097_interleaving_string.rs b/src/solution/s0097_interleaving_string.rs deleted file mode 100644 index 8d69d851..00000000 --- a/src/solution/s0097_interleaving_string.rs +++ /dev/null @@ -1,115 +0,0 @@ -/** - * [97] Interleaving String - * - * Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. - * - * Example 1: - * - * - * Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" - * Output: true - * - * - * Example 2: - * - * - * Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" - * Output: false - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/interleaving-string/ -// discuss: https://leetcode.com/problems/interleaving-string/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// DFS with memorization -/* -思路: DFS, 三个指针 i,j,k 分别指向 s1, s2, s3 已经消费到的 char 位置, 下一个可以走的路径是 s3 当前消费到的 char 值 - -如 aaaaaas aaaaaaaw aaaaaaaaaaaaaasw -那么第一步可以从 s1 或 s2 取一个 char, 用 DFS 的方式搜索整个解空间 - -优化: 直接 DFS 非常慢, 还是上面的例子, 最差情况是大量重复字符, 时间复杂度直接是 2^(M+N), 优化方式借鉴 DP 经常用到的 -memorize, 使用一个二维数组缓存每一对遍历过的 i,j 最后是否能产生合法的 interleaving. - -优化后通过缓存剪除的路径比较难分析, 但很显然能知道最差情况也只需要将所有 M*N 的组合进行标记, 因此最差时间复杂度 O(M*N) -空间复杂度 O(M*N) -*/ - -impl Solution { - pub fn is_interleave(s1: String, s2: String, s3: String) -> bool { - let mut cache = vec![vec![false; s2.len() + 1]; s1.len() + 1]; - Solution::dfs( - &s1.chars().collect(), - &s2.chars().collect(), - &s3.chars().collect(), - 0, - 0, - 0, - &mut cache, - ) - } - - fn dfs( - s1: &Vec, - s2: &Vec, - s3: &Vec, - i: usize, - j: usize, - k: usize, - invalid: &mut Vec>, - ) -> bool { - if invalid[i][j] { - return false; - } - if i == s1.len() && j == s2.len() && k == s3.len() { - return true; - } - let valid = (i < s1.len() - && k < s3.len() - && s1[i] == s3[k] - && Solution::dfs(s1, s2, s3, i + 1, j, k + 1, invalid)) - || (j < s2.len() - && k < s3.len() - && s2[j] == s3[k] - && Solution::dfs(s1, s2, s3, i, j + 1, k + 1, invalid)); - if !valid { - invalid[i][j] = true - } - valid - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_97() { - assert_eq!( - Solution::is_interleave( - "aabcc".to_owned(), - "dbbca".to_owned(), - "aadbbcbcac".to_owned() - ), - true - ); - assert_eq!( - Solution::is_interleave( - "aabcc".to_owned(), - "dbbca".to_owned(), - "aadbbbaccc".to_owned() - ), - false - ); - assert_eq!( - Solution::is_interleave("a".to_owned(), "b".to_owned(), "a".to_owned()), - false - ); - } -} diff --git a/src/solution/s0098_validate_binary_search_tree.rs b/src/solution/s0098_validate_binary_search_tree.rs deleted file mode 100644 index 09098c18..00000000 --- a/src/solution/s0098_validate_binary_search_tree.rs +++ /dev/null @@ -1,97 +0,0 @@ -/** - * [98] Validate Binary Search Tree - * - * Given a binary tree, determine if it is a valid binary search tree (BST). - * - * Assume a BST is defined as follows: - * - * - * The left subtree of a node contains only nodes with keys less than the node's key. - * The right subtree of a node contains only nodes with keys greater than the node's key. - * Both the left and right subtrees must also be binary search trees. - * - * - * Example 1: - * - * - * Input: - * 2 - * / \ - * 1 3 - * Output: true - * - * - * Example 2: - * - * - * 5 - * / \ - * 1 4 - * / \ - * 3 6 - * Output: false - * Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value - * is 5 but its right child's value is 4. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/validate-binary-search-tree/ -// discuss: https://leetcode.com/problems/validate-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for a binary tree node. -use crate::util::tree::{to_tree, TreeNode}; - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn is_valid_bst(root: Option>>) -> bool { - let mut vec = vec![]; - Solution::preorder_traverse(root.as_ref(), &mut vec) - } - - fn preorder_traverse( - root: Option<&Rc>>, - formers: &mut Vec<(i32, i32)>, - ) -> bool { - if let Some(node) = root { - let root_val = root.as_ref().unwrap().borrow().val; - for former in formers.iter() { - if (former.0 < 0 && root_val >= former.1) || (former.0 > 0 && root_val <= former.1) - { - return false; - } - } - let mut to_right = formers.clone(); - formers.push((-1, root_val)); - to_right.push((1, root_val)); - Solution::preorder_traverse(node.borrow().left.as_ref(), formers) - && Solution::preorder_traverse(node.borrow().right.as_ref(), &mut to_right) - } else { - true - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_98() { - assert_eq!( - Solution::is_valid_bst(tree![5, 1, 4, null, null, 3, 6]), - false - ); - assert_eq!(Solution::is_valid_bst(tree![2, 1, 3]), true); - assert_eq!( - Solution::is_valid_bst(tree![10, 5, 15, null, null, 6, 20]), - false - ); - } -} diff --git a/src/solution/s0099_recover_binary_search_tree.rs b/src/solution/s0099_recover_binary_search_tree.rs deleted file mode 100644 index 2401231a..00000000 --- a/src/solution/s0099_recover_binary_search_tree.rs +++ /dev/null @@ -1,162 +0,0 @@ -/** - * [99] Recover Binary Search Tree - * - * Two elements of a binary search tree (BST) are swapped by mistake. - * - * Recover the tree without changing its structure. - * - * Example 1: - * - * - * Input: [1,3,null,null,2] - * - * 1 - * / - * 3 - * \ - * 2 - * - * Output: [3,1,null,null,2] - * - * 3 - * / - * 1 - * \ - * 2 - * - * - * Example 2: - * - * - * Input: [3,1,4,null,null,2] - * - * 3 - * / \ - * 1 4 - * / - * 2 - * - * Output: [2,1,4,null,null,3] - * - * 2 - * / \ - * 1 4 - * / - * 3 - * - * - * Follow up: - * - * - * A solution using O(n) space is pretty straight forward. - * Could you devise a constant space solution? - * - * - */ -pub struct Solution {} - -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/recover-binary-search-tree/ -// discuss: https://leetcode.com/problems/recover-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -基本思路: 对 root, 收集左右两侧的节点值: - - - 右侧有值小于 root, 左侧有值大于 root: 交换这两个值 - - 一侧有值不合法, 另一侧合法: 交换不合法的值与 root - - 两侧都合法: 递归对左右子树进行上述操作 - -直接使用上述思路会重复迭代子树, 因此可以先用一次中序遍历, 将值的分布记录在数组中, 之后可以用 O(1) 的时间得到某个 node 两侧的值分布 - -这种办法的时间空间复杂度都是 O(N) - -原题中的 follow up 部分提出可以想一个常数空间复杂度的算法, 因此可以继续优化. - -最开始的办法会重复迭代子树是因为 Top-down, 可以尝试一下 Bottom-up 能不能解决问题: - -- 后序遍历递归校验每个 node 是否合法 -- 假如 node 合法, 那么只需要把这个子树中的最大值和最小值返回到上一个层级来帮助判断上一个层级的子树是否合法即可, 无需记录这个子树的所有值 -- 假如 node 不合法, 按最开始的办法进行处理, 除非... -- 只有一侧值不合法, 这时候由于是 Bottom-up, 不能直接交换不合法的值与 root, 而要判断交换后能否合法(Top-down 的办法中由于题目给定了有且仅有 swap 一次, 因此与 root 交换必然是合法的) - -这个办法时间复杂度 O(N), 空间 O(1). 题解就用 Bottom-up 来写. - */ -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn recover_tree(root: &mut Option>>) { - Solution::recover_helper(root.as_ref()); - } - - fn recover_helper( - root: Option<&Rc>>, - ) -> ( - Option>>, - Option>>, - bool, - ) { - if let Some(node) = root { - let (l_min, l_max, l_flag) = Solution::recover_helper(node.borrow().left.as_ref()); - let (r_min, r_max, r_flag) = Solution::recover_helper(node.borrow().right.as_ref()); - // we've already find a swap, return quickly - if l_flag || r_flag { - return (None, None, true); - } - let root_val = node.borrow().val; - let l_err = l_max.as_ref().map_or(false, |v| v.borrow().val > root_val); - let r_err = r_min.as_ref().map_or(false, |v| v.borrow().val < root_val); - // invalid sub-tree found, do swap - if l_err || r_err { - if l_err && r_err { - } else if l_err { - std::mem::swap( - &mut l_max.unwrap().borrow_mut().val, - &mut node.borrow_mut().val, - ); - } else if r_err { - std::mem::swap( - &mut r_min.unwrap().borrow_mut().val, - &mut node.borrow_mut().val, - ) - } - return (None, None, true); - } - ( - if l_min.is_some() { - l_min - } else { - Some(node.clone()) - }, - if r_max.is_some() { - r_max - } else { - Some(node.clone()) - }, - false, - ) - } else { - (None, None, false) - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_99() { - let mut tree = tree![3, 1, 4, null, null, 2]; - Solution::recover_tree(&mut tree); - assert_eq!(tree, tree![2, 1, 4, null, null, 3]); - - let mut tree = tree![2, 6, 5, null, null, 3, 1, null, 4]; - Solution::recover_tree(&mut tree); - assert_eq!(tree, tree![2, 1, 5, null, null, 3, 6, null, 4]); - } -} diff --git a/src/solution/s0100_same_tree.rs b/src/solution/s0100_same_tree.rs deleted file mode 100644 index c7dc1372..00000000 --- a/src/solution/s0100_same_tree.rs +++ /dev/null @@ -1,76 +0,0 @@ -/** - * [100] Same Tree - * - * Given two binary trees, write a function to check if they are the same or not. - * - * Two binary trees are considered the same if they are structurally identical and the nodes have the same value. - * - * Example 1: - * - * - * Input: 1 1 - * / \ / \ - * 2 3 2 3 - * - * [1,2,3], [1,2,3] - * - * Output: true - * - * - * Example 2: - * - * - * Input: 1 1 - * / \ - * 2 2 - * - * [1,2], [1,null,2] - * - * Output: false - * - * - * Example 3: - * - * - * Input: 1 1 - * / \ / \ - * 2 1 1 2 - * - * [1,2,1], [1,1,2] - * - * Output: false - * - * - */ -pub struct Solution {} - -use crate::util::tree::{to_tree, TreeNode}; -// problem: https://leetcode.com/problems/same-tree/ -// discuss: https://leetcode.com/problems/same-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn is_same_tree( - p: Option>>, - q: Option>>, - ) -> bool { - p == q - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_100() { - assert_eq!( - Solution::is_same_tree(tree![1, 2, 3, 4, null, 5], tree![1, 2, 3, 4, null, 5]), - true - ) - } -} diff --git a/src/solution/s0101_symmetric_tree.rs b/src/solution/s0101_symmetric_tree.rs deleted file mode 100644 index 41f44bc8..00000000 --- a/src/solution/s0101_symmetric_tree.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [101] Symmetric Tree - * - * Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). - * - * - * For example, this binary tree [1,2,2,3,4,4,3] is symmetric: - * - * 1 - * / \ - * 2 2 - * / \ / \ - * 3 4 4 3 - * - * - * - * But the following [1,2,2,null,3,null,3] is not:
- * - * 1 - * / \ - * 2 2 - * \ \ - * 3 3 - * - * - * - * - * Note:
- * Bonus points if you could solve it both recursively and iteratively. - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/symmetric-tree/ -// discuss: https://leetcode.com/problems/symmetric-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn is_symmetric(root: Option>>) -> bool { - Solution::symmetric_helper( - root.as_ref().and_then(|v| v.borrow().left.clone()), - root.as_ref().and_then(|v| v.borrow().right.clone()), - ) - } - - fn symmetric_helper( - left: Option>>, - right: Option>>, - ) -> bool { - match (left, right) { - (Some(left), Some(right)) => { - left.borrow().val == right.borrow().val - && Solution::symmetric_helper( - left.borrow().left.clone(), - right.borrow().right.clone(), - ) - && Solution::symmetric_helper( - left.borrow().right.clone(), - right.borrow().left.clone(), - ) - } - (None, None) => true, - _ => false, - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_101() { - assert_eq!(Solution::is_symmetric(tree![1, 2, 2, 3, 4, 4, 3]), true); - assert_eq!( - Solution::is_symmetric(tree![1, 2, 2, null, 3, null, 3]), - false - ); - assert_eq!(Solution::is_symmetric(tree![]), true); - } -} diff --git a/src/solution/s0102_binary_tree_level_order_traversal.rs b/src/solution/s0102_binary_tree_level_order_traversal.rs deleted file mode 100644 index a5a3fd13..00000000 --- a/src/solution/s0102_binary_tree_level_order_traversal.rs +++ /dev/null @@ -1,81 +0,0 @@ -/** - * [102] Binary Tree Level Order Traversal - * - * Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). - * - * - * For example:
- * Given binary tree [3,9,20,null,null,15,7],
- * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * - * - * return its level order traversal as:
- * - * [ - * [3], - * [9,20], - * [15,7] - * ] - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-level-order-traversal/ -// discuss: https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn level_order(root: Option>>) -> Vec> { - let mut res = Vec::new(); - let mut current_level = 0; - if root.is_none() { - return res; - } - let mut deq = VecDeque::new(); - deq.push_back((0, root.clone())); - let mut vec = Vec::new(); - while !deq.is_empty() { - if let Some((level, Some(node))) = deq.pop_front() { - deq.push_back((level + 1, node.borrow().left.clone())); - deq.push_back((level + 1, node.borrow().right.clone())); - if level > current_level { - res.push(vec); - vec = Vec::new(); - current_level = level; - } - vec.push(node.borrow().val); - } - } - if !vec.is_empty() { - res.push(vec) - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_102() { - assert_eq!( - Solution::level_order(tree![3, 9, 20, null, null, 15, 7]), - vec![vec![3], vec![9, 20], vec![15, 7]] - ); - } -} diff --git a/src/solution/s0103_binary_tree_zigzag_level_order_traversal.rs b/src/solution/s0103_binary_tree_zigzag_level_order_traversal.rs deleted file mode 100644 index 78aa7b5e..00000000 --- a/src/solution/s0103_binary_tree_zigzag_level_order_traversal.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [103] Binary Tree Zigzag Level Order Traversal - * - * Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). - * - * - * For example:
- * Given binary tree [3,9,20,null,null,15,7],
- * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * - * - * return its zigzag level order traversal as:
- * - * [ - * [3], - * [20,9], - * [15,7] - * ] - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ -// discuss: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn zigzag_level_order(root: Option>>) -> Vec> { - let mut res = Vec::new(); - let mut current_level = 0; - if root.is_none() { - return res; - } - let mut deq = VecDeque::new(); - deq.push_back((0, root.clone())); - let mut vec = Vec::new(); - while !deq.is_empty() { - if let Some((level, Some(node))) = deq.pop_front() { - deq.push_back((level + 1, node.borrow().left.clone())); - deq.push_back((level + 1, node.borrow().right.clone())); - if level > current_level { - if current_level % 2 == 1 { - vec.reverse(); - } - res.push(vec); - vec = Vec::new(); - current_level = level; - } - vec.push(node.borrow().val); - } - } - if !vec.is_empty() { - if current_level % 2 == 1 { - vec.reverse(); - } - res.push(vec) - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_103() { - assert_eq!( - Solution::zigzag_level_order(tree![3, 9, 20, null, null, 15, 7]), - vec![vec![3], vec![20, 9], vec![15, 7]] - ); - } -} diff --git a/src/solution/s0104_maximum_depth_of_binary_tree.rs b/src/solution/s0104_maximum_depth_of_binary_tree.rs deleted file mode 100644 index 2b2a51d4..00000000 --- a/src/solution/s0104_maximum_depth_of_binary_tree.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [104] Maximum Depth of Binary Tree - * - * Given a binary tree, find its maximum depth. - * - * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. - * - * Note: A leaf is a node with no children. - * - * Example: - * - * Given binary tree [3,9,20,null,null,15,7], - * - * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * return its depth = 3. - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/maximum-depth-of-binary-tree/ -// discuss: https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn max_depth(root: Option>>) -> i32 { - let mut max = 0; - Solution::depth_helper(root.as_ref(), &mut max, 0); - max - } - - fn depth_helper(root: Option<&Rc>>, max: &mut i32, curr: i32) { - if let Some(node) = root { - *max = i32::max(*max, curr + 1); - Solution::depth_helper(node.borrow().left.as_ref(), max, curr + 1); - Solution::depth_helper(node.borrow().right.as_ref(), max, curr + 1); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_104() { - assert_eq!(Solution::max_depth(tree![]), 0); - assert_eq!(Solution::max_depth(tree![3, 9, 20, null, null, 15, 7]), 3); - } -} diff --git a/src/solution/s0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs b/src/solution/s0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs deleted file mode 100644 index 809ae654..00000000 --- a/src/solution/s0105_construct_binary_tree_from_preorder_and_inorder_traversal.rs +++ /dev/null @@ -1,71 +0,0 @@ -/** - * [105] Construct Binary Tree from Preorder and Inorder Traversal - * - * Given preorder and inorder traversal of a tree, construct the binary tree. - * - * Note:
- * You may assume that duplicates do not exist in the tree. - * - * For example, given - * - * - * preorder = [3,9,20,15,7] - * inorder = [9,3,15,20,7] - * - * Return the following binary tree: - * - * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ -// discuss: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn build_tree(preorder: Vec, inorder: Vec) -> Option>> { - Solution::build_tree_helper(&preorder[..], &inorder[..]) - } - - fn build_tree_helper(preorder: &[i32], inorder: &[i32]) -> Option>> { - if preorder.is_empty() { - return None; - } - let root_idx = inorder.iter().position(|&v| v == preorder[0]).unwrap(); - Some(Rc::new(RefCell::new(TreeNode { - val: preorder[0], - left: Solution::build_tree_helper(&preorder[1..root_idx + 1], &inorder[0..root_idx]), - right: Solution::build_tree_helper(&preorder[root_idx + 1..], &inorder[root_idx + 1..]), - }))) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_105() { - assert_eq!( - Solution::build_tree(vec![3, 9, 20, 15, 7], vec![9, 3, 15, 20, 7]), - tree![3, 9, 20, null, null, 15, 7] - ); - assert_eq!( - Solution::build_tree(vec![3, 20, 7], vec![3, 20, 7]), - tree![3, null, 20, null, 7] - ); - assert_eq!(Solution::build_tree(vec![], vec![]), tree![]); - } -} diff --git a/src/solution/s0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs b/src/solution/s0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs deleted file mode 100644 index df215bbc..00000000 --- a/src/solution/s0106_construct_binary_tree_from_inorder_and_postorder_traversal.rs +++ /dev/null @@ -1,78 +0,0 @@ -/** - * [106] Construct Binary Tree from Inorder and Postorder Traversal - * - * Given inorder and postorder traversal of a tree, construct the binary tree. - * - * Note:
- * You may assume that duplicates do not exist in the tree. - * - * For example, given - * - * - * inorder = [9,3,15,20,7] - * postorder = [9,15,7,20,3] - * - * Return the following binary tree: - * - * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ -// discuss: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn build_tree(inorder: Vec, postorder: Vec) -> Option>> { - Solution::build_tree_helper(&postorder[..], &inorder[..]) - } - - fn build_tree_helper(postorder: &[i32], inorder: &[i32]) -> Option>> { - if postorder.is_empty() { - return None; - } - let root_idx = inorder - .iter() - .position(|v| v == postorder.last().unwrap()) - .unwrap(); - Some(Rc::new(RefCell::new(TreeNode { - val: *postorder.last().unwrap(), - left: Solution::build_tree_helper(&postorder[0..root_idx], &inorder[0..root_idx]), - right: Solution::build_tree_helper( - &postorder[root_idx..postorder.len() - 1], - &inorder[root_idx + 1..], - ), - }))) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_106() { - assert_eq!( - Solution::build_tree(vec![9, 3, 15, 20, 7], vec![9, 15, 7, 20, 3]), - tree![3, 9, 20, null, null, 15, 7] - ); - assert_eq!( - Solution::build_tree(vec![3, 20, 7], vec![7, 20, 3]), - tree![3, null, 20, null, 7] - ); - assert_eq!(Solution::build_tree(vec![], vec![]), tree![]); - } -} diff --git a/src/solution/s0107_binary_tree_level_order_traversal_ii.rs b/src/solution/s0107_binary_tree_level_order_traversal_ii.rs deleted file mode 100644 index 4b74e0d7..00000000 --- a/src/solution/s0107_binary_tree_level_order_traversal_ii.rs +++ /dev/null @@ -1,82 +0,0 @@ -/** - * [107] Binary Tree Level Order Traversal II - * - * Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). - * - * - * For example:
- * Given binary tree [3,9,20,null,null,15,7],
- * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * - * - * return its bottom-up level order traversal as:
- * - * [ - * [15,7], - * [9,20], - * [3] - * ] - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-level-order-traversal-ii/ -// discuss: https://leetcode.com/problems/binary-tree-level-order-traversal-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn level_order_bottom(root: Option>>) -> Vec> { - let mut res = Vec::new(); - let mut current_level = 0; - if root.is_none() { - return res; - } - let mut deq = VecDeque::new(); - deq.push_back((0, root.clone())); - let mut vec = Vec::new(); - while !deq.is_empty() { - if let Some((level, Some(node))) = deq.pop_front() { - deq.push_back((level + 1, node.borrow().left.clone())); - deq.push_back((level + 1, node.borrow().right.clone())); - if level > current_level { - res.push(vec); - vec = Vec::new(); - current_level = level; - } - vec.push(node.borrow().val); - } - } - if !vec.is_empty() { - res.push(vec) - } - res.reverse(); - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_107() { - assert_eq!( - Solution::level_order_bottom(tree![3, 9, 20, null, null, 15, 7]), - vec![vec![15, 7], vec![9, 20], vec![3],] - ); - } -} diff --git a/src/solution/s0108_convert_sorted_array_to_binary_search_tree.rs b/src/solution/s0108_convert_sorted_array_to_binary_search_tree.rs deleted file mode 100644 index 2cefab5c..00000000 --- a/src/solution/s0108_convert_sorted_array_to_binary_search_tree.rs +++ /dev/null @@ -1,64 +0,0 @@ -/** - * [108] Convert Sorted Array to Binary Search Tree - * - * Given an array where elements are sorted in ascending order, convert it to a height balanced BST. - * - * 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. - * - * Example: - * - * - * Given the sorted array: [-10,-3,0,5,9], - * - * One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: - * - * 0 - * / \ - * -3 9 - * / / - * -10 5 - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ -// discuss: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn sorted_array_to_bst(nums: Vec) -> Option>> { - Solution::bst_helper(&nums[..]) - } - - fn bst_helper(nums: &[i32]) -> Option>> { - if nums.is_empty() { - return None; - } - Some(Rc::new(RefCell::new(TreeNode { - val: nums[nums.len() / 2], - left: Solution::bst_helper(&nums[0..(nums.len() / 2)]), - right: Solution::bst_helper(&nums[(nums.len() / 2 + 1)..]), - }))) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_108() { - assert_eq!( - Solution::sorted_array_to_bst(vec![-10, -3, 0, 5, 9]), - tree![0, -3, 9, -10, null, 5] - ); - assert_eq!(Solution::sorted_array_to_bst(vec![]), tree![]); - } -} diff --git a/src/solution/s0109_convert_sorted_list_to_binary_search_tree.rs b/src/solution/s0109_convert_sorted_list_to_binary_search_tree.rs deleted file mode 100644 index e2070965..00000000 --- a/src/solution/s0109_convert_sorted_list_to_binary_search_tree.rs +++ /dev/null @@ -1,70 +0,0 @@ -/** - * [109] Convert Sorted List to Binary Search Tree - * - * Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. - * - * 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. - * - * Example: - * - * - * Given the sorted linked list: [-10,-3,0,5,9], - * - * One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: - * - * 0 - * / \ - * -3 9 - * / / - * -10 5 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ -// discuss: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn sorted_list_to_bst(head: Option>) -> Option>> { - let mut arr = Vec::new(); - let mut head = head; - while let Some(node) = head { - arr.push(node.val); - head = node.next; - } - Solution::bst_helper(&arr[..]) - } - - fn bst_helper(nums: &[i32]) -> Option>> { - if nums.is_empty() { - return None; - } - Some(Rc::new(RefCell::new(TreeNode { - val: nums[nums.len() / 2], - left: Solution::bst_helper(&nums[0..(nums.len() / 2)]), - right: Solution::bst_helper(&nums[(nums.len() / 2 + 1)..]), - }))) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_109() { - assert_eq!( - Solution::sorted_list_to_bst(linked![-10, -3, 0, 5, 9]), - tree![0, -3, 9, -10, null, 5] - ); - } -} diff --git a/src/solution/s0110_balanced_binary_tree.rs b/src/solution/s0110_balanced_binary_tree.rs deleted file mode 100644 index c3171126..00000000 --- a/src/solution/s0110_balanced_binary_tree.rs +++ /dev/null @@ -1,97 +0,0 @@ -/** - * [110] Balanced Binary Tree - * - * Given a binary tree, determine if it is height-balanced. - * - * 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. - *
- * - * Example 1: - * - * Given the following tree [3,9,20,null,null,15,7]: - * - * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * Return true.
- *
- * Example 2: - * - * Given the following tree [1,2,2,3,3,null,null,4,4]: - * - * - * 1 - * / \ - * 2 2 - * / \ - * 3 3 - * / \ - * 4 4 - * - * - * Return false. - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/balanced-binary-tree/ -// discuss: https://leetcode.com/problems/balanced-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn is_balanced(root: Option>>) -> bool { - Solution::balanced_helper(root.as_ref()).is_some() - } - - fn balanced_helper(root: Option<&Rc>>) -> Option { - if let Some(node) = root { - let pair = ( - Solution::balanced_helper(node.borrow().left.as_ref()), - Solution::balanced_helper(node.borrow().right.as_ref()), - ); - match pair { - (Some(left), Some(right)) => { - if i32::abs(left - right) < 2 { - return Some(i32::max(left, right) + 1); - } else { - return None; - } - } - _ => return None, - } - } else { - Some(0) - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_110() { - assert_eq!(Solution::is_balanced(tree![]), true); - assert_eq!( - Solution::is_balanced(tree![3, 9, 20, null, null, 15, 7]), - true - ); - assert_eq!( - Solution::is_balanced(tree![1, 2, 2, 3, 3, null, null, 4, 4]), - false - ); - } -} diff --git a/src/solution/s0111_minimum_depth_of_binary_tree.rs b/src/solution/s0111_minimum_depth_of_binary_tree.rs deleted file mode 100644 index a73e49f0..00000000 --- a/src/solution/s0111_minimum_depth_of_binary_tree.rs +++ /dev/null @@ -1,65 +0,0 @@ -/** - * [111] Minimum Depth of Binary Tree - * - * Given a binary tree, find its minimum depth. - * - * The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. - * - * Note: A leaf is a node with no children. - * - * Example: - * - * Given binary tree [3,9,20,null,null,15,7], - * - * - * 3 - * / \ - * 9 20 - * / \ - * 15 7 - * - * return its minimum depth = 2. - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/minimum-depth-of-binary-tree/ -// discuss: https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn min_depth(root: Option>>) -> i32 { - if root.is_none() { - return 0; - } - let mut deq = VecDeque::new(); - deq.push_back((1, root.clone())); - while !deq.is_empty() { - if let Some((level, Some(node))) = deq.pop_front() { - if node.borrow().left.is_none() && node.borrow().right.is_none() { - return level; - } - deq.push_back((level + 1, node.borrow().left.clone())); - deq.push_back((level + 1, node.borrow().right.clone())); - } - } - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_111() { - assert_eq!(Solution::min_depth(tree![3, 9, 20, null, null, 15, 7]), 2); - } -} diff --git a/src/solution/s0112_path_sum.rs b/src/solution/s0112_path_sum.rs deleted file mode 100644 index e2e0a235..00000000 --- a/src/solution/s0112_path_sum.rs +++ /dev/null @@ -1,80 +0,0 @@ -/** - * [112] Path Sum - * - * Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. - * - * Note: A leaf is a node with no children. - * - * Example: - * - * Given the below binary tree and sum = 22, - * - * - * 5 - * / \ - * 4 8 - * / / \ - * 11 13 4 - * / \ \ - * 7 2 1 - * - * - * return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/path-sum/ -// discuss: https://leetcode.com/problems/path-sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn has_path_sum(root: Option>>, sum: i32) -> bool { - if root.is_none() { - return false; - } - let mut deq = VecDeque::new(); - deq.push_back((0, root.unwrap().clone())); - while !deq.is_empty() { - if let Some((acc, node)) = deq.pop_front() { - let acc = acc + node.borrow().val; - if node.borrow().left.is_none() && node.borrow().right.is_none() { - if acc == sum { - return true; - } - } else { - if node.borrow().left.is_some() { - deq.push_back((acc, node.borrow().left.as_ref().unwrap().clone())) - }; - if node.borrow().right.is_some() { - deq.push_back((acc, node.borrow().right.as_ref().unwrap().clone())) - }; - } - } - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_112() { - assert_eq!( - Solution::has_path_sum( - tree![5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], - 22 - ), - true - ); - } -} diff --git a/src/solution/s0113_path_sum_ii.rs b/src/solution/s0113_path_sum_ii.rs deleted file mode 100644 index 106d1921..00000000 --- a/src/solution/s0113_path_sum_ii.rs +++ /dev/null @@ -1,86 +0,0 @@ -/** - * [113] Path Sum II - * - * Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. - * - * Note: A leaf is a node with no children. - * - * Example: - * - * Given the below binary tree and sum = 22, - * - * - * 5 - * / \ - * 4 8 - * / / \ - * 11 13 4 - * / \ / \ - * 7 2 5 1 - * - * - * Return: - * - * - * [ - * [5,4,11,2], - * [5,8,4,5] - * ] - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/path-sum-ii/ -// discuss: https://leetcode.com/problems/path-sum-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn path_sum(root: Option>>, sum: i32) -> Vec> { - let mut res = Vec::new(); - if root.is_none() { - return res; - } - let mut deq = VecDeque::new(); - deq.push_back((0, Vec::new(), root.clone())); - while !deq.is_empty() { - if let Some((acc, mut vec, Some(node))) = deq.pop_front() { - let acc = acc + node.borrow().val; - vec.push(node.borrow().val); - if node.borrow().left.is_none() && node.borrow().right.is_none() { - if acc == sum { - res.push(vec); - } - } else { - if node.borrow().left.is_some() { - deq.push_back((acc, vec.clone(), node.borrow().left.clone())); - } - if node.borrow().right.is_some() { - deq.push_back((acc, vec.clone(), node.borrow().right.clone())); - } - } - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_113() { - assert_eq!( - Solution::path_sum(tree![5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1], 22), - vec![vec![5, 4, 11, 2], vec![5, 8, 4, 5]] - ) - } -} diff --git a/src/solution/s0114_flatten_binary_tree_to_linked_list.rs b/src/solution/s0114_flatten_binary_tree_to_linked_list.rs deleted file mode 100644 index 63668c47..00000000 --- a/src/solution/s0114_flatten_binary_tree_to_linked_list.rs +++ /dev/null @@ -1,90 +0,0 @@ -/** - * [114] Flatten Binary Tree to Linked List - * - * Given a binary tree, flatten it to a linked list in-place. - * - * For example, given the following tree: - * - * - * 1 - * / \ - * 2 5 - * / \ \ - * 3 4 6 - * - * - * The flattened tree should look like: - * - * - * 1 - * \ - * 2 - * \ - * 3 - * \ - * 4 - * \ - * 5 - * \ - * 6 - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ -// discuss: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn flatten(root: &mut Option>>) { - Solution::flatten_helper(root.clone()); - } - - fn flatten_helper(root: Option>>) -> Option>> { - if let Some(node) = root { - let tail = Solution::flatten_helper(node.borrow().left.clone()); - Solution::flatten_helper(node.borrow_mut().right.clone()); - let mut right = node.borrow().right.clone(); - let mut ptr = node.clone(); - if let Some(tail) = tail { - let head = node.borrow_mut().left.take(); - node.borrow_mut().right = head; - tail.borrow_mut().right = right.clone(); - ptr = tail.clone(); - } - while let Some(next) = ptr.clone().borrow().right.clone() { - ptr = next - } - Some(ptr) - } else { - None - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_114() { - let mut tree = tree![1, 2, 5, 3, 4, null, 6]; - Solution::flatten(&mut tree); - assert_eq!(tree, tree![1, null, 2, null, 3, null, 4, null, 5, null, 6]); - - let mut tree = tree![1, 2, null, 3]; - Solution::flatten(&mut tree); - assert_eq!(tree, tree![1, null, 2, null, 3]); - - let mut tree = tree![1, null, 2, 3]; - Solution::flatten(&mut tree); - assert_eq!(tree, tree![1, null, 2, null, 3]); - } -} diff --git a/src/solution/s0115_distinct_subsequences.rs b/src/solution/s0115_distinct_subsequences.rs deleted file mode 100644 index 7af3d08b..00000000 --- a/src/solution/s0115_distinct_subsequences.rs +++ /dev/null @@ -1,122 +0,0 @@ -/** - * [115] Distinct Subsequences - * - * Given a string S and a string T, count the number of distinct subsequences of S which equals T. - * - * A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). - * - * Example 1: - * - * - * Input: S = "rabbbit", T = "rabbit" - * Output: 3 - * Explanation: - * - * As shown below, there are 3 ways you can generate "rabbit" from S. - * (The caret symbol ^ means the chosen letters) - * - * rabbbit - * ^^^^ ^^ - * rabbbit - * ^^ ^^^^ - * rabbbit - * ^^^ ^^^ - * - * - * Example 2: - * - * - * Input: S = "babgbag", T = "bag" - * Output: 5 - * Explanation: - * - * As shown below, there are 5 ways you can generate "bag" from S. - * (The caret symbol ^ means the chosen letters) - * - * babgbag - * ^^ ^ - * babgbag - * ^^ ^ - * babgbag - * ^ ^^ - * babgbag - * ^ ^^ - * babgbag - * ^^^ - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/distinct-subsequences/ -// discuss: https://leetcode.com/problems/distinct-subsequences/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -首先想到 DFS. 但这里 DFS 有重复计算, 因为我们不需要列出所有的路径, 复杂度可以考虑 "aaaaaaaaaaaaaaaaaaaa" -里找 "aaaaaaaaa", 直接搜索的话复杂度是指数级的(阶乘), 原因很明显, 这本身是个排列组合, 可以套 combination 公式 -20! / ((20-10)! * 10!) 得到结果是 184756 - -要把复杂度从指数级降下来, 那么必须干掉重复计算, 那就想到 memorize, 想到 memorize 就想到 DP 和 Bottom-Up 递推, -回顾一下 #62 和 #63 这两个问题 (unique paths), 使用的是Bottom-Up DP, 到达每个格子的可能路径是上下两个格子的 -可能路径的和. 这里就跳过了很多的计算, 不需要把每条路径都遍历出来了. 在 unique paths 问题中, 到达右下角的路径数的 -子问题是到达右下角左侧格子的路径数以及到达右下角上侧格子的路径数. 这个问题也是一样的道理, s 中找子序列 t: - -* s[0..i] 包含的 t 序列数就是所有 s[0..j] (j < i) 包含的 t[0..t.len()-1] 的序列数 - -以 babgbag 中找 bag 为例, 做一次 Bottom-Up 递推: - - b a b g b a g -b 1 1 1 3 找 'b' 这个子序列, 那么以 [0, 2, 4] 这三个下标结尾各有一种 -a 1 3 4 找 'ba' 这个子序列, 那么以 1 结尾有1种(0 < 1), 以 5 结尾有 3 种 (0,2,4 都 < 5) -g 1 4 5 同理, 以 3 结尾有 1 种, 以 6 结尾有 4 种, 共 5 种 - -显然, 计算第 N 行时只依赖第 N-1 行的结果, 因此我们不需要存储整个矩阵, 只需要存储一行即可 - -时间复杂度是 O(M*N), 空间复杂度是 O(M) -*/ -impl Solution { - pub fn num_distinct(s: String, t: String) -> i32 { - let s = s.chars().collect::>(); - let mut cache = vec![0; s.len()]; - for (i, ch) in t.chars().into_iter().enumerate() { - let mut acc = 0; - // first char initialization - if i == 0 { - for i in 0..s.len() { - if ch == s[i] { - cache[i] = 1 - } - } - continue; - } - for i in 0..s.len() { - let new_acc = acc + cache[i]; - cache[i] = if s[i] == ch { acc } else { 0 }; - acc = new_acc; - } - } - cache.into_iter().fold(0, |acc, x| acc + x) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_115() { - //assert_eq!(Solution::num_distinct("rabbbit".to_owned(), "rabbit".to_owned()), 3); - assert_eq!( - Solution::num_distinct("babgbag".to_owned(), "bag".to_owned()), - 5 - ); - assert_eq!( - Solution::num_distinct("aaaaaaaaaaaaaaaaaaaa".to_owned(), "aaaaaaaaaa".to_owned()), - 184756 - ); - } -} diff --git a/src/solution/s0118_pascals_triangle.rs b/src/solution/s0118_pascals_triangle.rs deleted file mode 100644 index d593242d..00000000 --- a/src/solution/s0118_pascals_triangle.rs +++ /dev/null @@ -1,70 +0,0 @@ -/** - * [118] Pascal's Triangle - * - * Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. - * - *
- * In Pascal's triangle, each number is the sum of the two numbers directly above it. - * - * Example: - * - * - * Input: 5 - * Output: - * [ - * [1], - * [1,1], - * [1,2,1], - * [1,3,3,1], - * [1,4,6,4,1] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/pascals-triangle/ -// discuss: https://leetcode.com/problems/pascals-triangle/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn generate(num_rows: i32) -> Vec> { - let mut res = Vec::new(); - if num_rows < 1 { - return res; - } - let mut curr = vec![1]; - for _ in 0..num_rows { - let mut next = vec![1; curr.len() + 1]; - for i in 1..curr.len() { - next[i] = curr[i - 1] + curr[i]; - } - res.push(curr); - curr = next; - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_118() { - assert_eq!(Solution::generate(1), vec![vec![1]]); - assert_eq!( - Solution::generate(5), - vec![ - vec![1], - vec![1, 1], - vec![1, 2, 1], - vec![1, 3, 3, 1], - vec![1, 4, 6, 4, 1] - ] - ); - } -} diff --git a/src/solution/s0119_pascals_triangle_ii.rs b/src/solution/s0119_pascals_triangle_ii.rs deleted file mode 100644 index 588a9835..00000000 --- a/src/solution/s0119_pascals_triangle_ii.rs +++ /dev/null @@ -1,64 +0,0 @@ -/** - * [119] Pascal's Triangle II - * - * Given a non-negative index k where k ≤ 33, return the k^th index row of the Pascal's triangle. - * - * Note that the row index starts from 0. - * - *
- * In Pascal's triangle, each number is the sum of the two numbers directly above it. - * - * Example: - * - * - * Input: 3 - * Output: [1,3,3,1] - * - * - * Follow up: - * - * Could you optimize your algorithm to use only O(k) extra space? - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/pascals-triangle-ii/ -// discuss: https://leetcode.com/problems/pascals-triangle-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -in-place algorithm - -1 1 1 1 1 -1 2 1 1 1 -1 3 3 1 1 -1 4 6 4 1 -*/ -impl Solution { - pub fn get_row(row_index: i32) -> Vec { - let mut curr = vec![1; (row_index + 1) as usize]; - for i in 0..row_index + 1 { - let mut prev = 1; - for j in 1..i { - let temp = curr[j as usize]; - curr[j as usize] = temp + prev; - prev = temp; - } - } - curr - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_119() { - assert_eq!(Solution::get_row(0), vec![1]); - assert_eq!(Solution::get_row(4), vec![1, 4, 6, 4, 1]) - } -} diff --git a/src/solution/s0120_triangle.rs b/src/solution/s0120_triangle.rs deleted file mode 100644 index 93c38d33..00000000 --- a/src/solution/s0120_triangle.rs +++ /dev/null @@ -1,67 +0,0 @@ -/** - * [120] Triangle - * - * Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. - * - * For example, given the following triangle - * - * - * [ - * [2], - * [3,4], - * [6,5,7], - * [4,1,8,3] - * ] - * - * - * The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). - * - * Note: - * - * 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. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/triangle/ -// discuss: https://leetcode.com/problems/triangle/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn minimum_total(triangle: Vec>) -> i32 { - let mut cache = vec![0; triangle.len()]; - for row in triangle.iter() { - let mut prev = 0; - for i in 0..row.len() { - let temp = cache[i]; - cache[i] = if i == 0 { - cache[i] - } else if i == row.len() - 1 { - prev - } else { - i32::min(cache[i], prev) - } + row[i]; - prev = temp; - } - } - cache - .into_iter() - .fold(i32::max_value(), |min, x| i32::min(min, x)) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_120() { - assert_eq!( - Solution::minimum_total(vec![vec![2], vec![3, 4], vec![6, 5, 7], vec![4, 1, 8, 3]]), - 11 - ) - } -} diff --git a/src/solution/s0121_best_time_to_buy_and_sell_stock.rs b/src/solution/s0121_best_time_to_buy_and_sell_stock.rs deleted file mode 100644 index d5d3746d..00000000 --- a/src/solution/s0121_best_time_to_buy_and_sell_stock.rs +++ /dev/null @@ -1,62 +0,0 @@ -/** - * [121] Best Time to Buy and Sell Stock - * - * Say you have an array for which the i^th element is the price of a given stock on day i. - * - * 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. - * - * Note that you cannot sell a stock before you buy one. - * - * Example 1: - * - * - * Input: [7,1,5,3,6,4] - * Output: 5 - * Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. - * Not 7-1 = 6, as selling price needs to be larger than buying price. - * - * - * Example 2: - * - * - * Input: [7,6,4,3,1] - * Output: 0 - * Explanation: In this case, no transaction is done, i.e. max profit = 0. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ -// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn max_profit(prices: Vec) -> i32 { - let mut max = 0; - let mut curr = 0; - for i in 1..prices.len() { - curr = curr + prices[i] - prices[i - 1]; - if curr <= 0 { - curr = 0; - } else { - max = i32::max(max, curr); - } - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_121() { - assert_eq!(Solution::max_profit(vec![7, 1, 5, 3, 6, 4]), 5); - assert_eq!(Solution::max_profit(vec![7, 6, 4, 3, 1]), 0); - } -} diff --git a/src/solution/s0122_best_time_to_buy_and_sell_stock_ii.rs b/src/solution/s0122_best_time_to_buy_and_sell_stock_ii.rs deleted file mode 100644 index 803c71b6..00000000 --- a/src/solution/s0122_best_time_to_buy_and_sell_stock_ii.rs +++ /dev/null @@ -1,67 +0,0 @@ -/** - * [122] Best Time to Buy and Sell Stock II - * - * Say you have an array for which the i^th element is the price of a given stock on day i. - * - * 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). - * - * Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). - * - * Example 1: - * - * - * Input: [7,1,5,3,6,4] - * Output: 7 - * Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. - * Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. - * - * - * Example 2: - * - * - * Input: [1,2,3,4,5] - * Output: 4 - * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. - * Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are - * engaging multiple transactions at the same time. You must sell before buying again. - * - * - * Example 3: - * - * - * Input: [7,6,4,3,1] - * Output: 0 - * Explanation: In this case, no transaction is done, i.e. max profit = 0. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ -// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn max_profit(prices: Vec) -> i32 { - let mut max = 0; - for i in 1..prices.len() { - if prices[i] > prices[i - 1] { - max += prices[i] - prices[i - 1]; - } - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_122() { - assert_eq!(Solution::max_profit(vec![7, 1, 5, 3, 6, 4]), 7); - assert_eq!(Solution::max_profit(vec![1, 2, 3, 4, 5]), 4); - } -} diff --git a/src/solution/s0123_best_time_to_buy_and_sell_stock_iii.rs b/src/solution/s0123_best_time_to_buy_and_sell_stock_iii.rs deleted file mode 100644 index bb068273..00000000 --- a/src/solution/s0123_best_time_to_buy_and_sell_stock_iii.rs +++ /dev/null @@ -1,106 +0,0 @@ -/** - * [123] Best Time to Buy and Sell Stock III - * - * Say you have an array for which the i^th element is the price of a given stock on day i. - * - * Design an algorithm to find the maximum profit. You may complete at most two transactions. - * - * Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). - * - * Example 1: - * - * - * Input: [3,3,5,0,0,3,1,4] - * Output: 6 - * Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. - * Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. - * - * Example 2: - * - * - * Input: [1,2,3,4,5] - * Output: 4 - * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. - * Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are - * engaging multiple transactions at the same time. You must sell before buying again. - * - * - * Example 3: - * - * - * Input: [7,6,4,3,1] - * Output: 0 - * Explanation: In this case, no transaction is done, i.e. max profit = 0. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ -// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -先考虑只进行 1 次交易的情况, 我们求以 i *为售出点*, 只进行 1 次交易获得的最大利润, 那么: - -f[i] = if f[i-1] > 0 { f[i-1] } else { 0 } + prices[i] - prices[i-1] - -这很容易解, 解完之后找出 f 里的最大值即可, 但这不容易推广到 K 次交易的情况, 因为这时 f[i] 不代表到 i *为止*的最大利润, 无法作为单独的交易帮助递推 -(到 i 为止的含义是售出点可以在 [0,i] 之间) - -我们可以稍作改进, 变成求以 i 为结束点, 只进行 1 次交易获得的最大利润, 那么: - -f[i] = max( - f[i-1], - prices[i] - min(prices[j] { j in [0, i-1] }) -) - -这仍然是一个 O(N) 的解法, 因为 min(prices[j] { j in [0, i-1] }) 不需要遍历, 可以在递推过程中直接维护好 - -现在再推广到进行 K 次交易的情况, 那我们要求以 i 为结束点, 进行 k 次交易获得的最大利润, 这时有了变化, 我们可以在 j 之前再进行 K - 1 次交易: - -f[k, i] = max( - f[k, i-1], - prices[i] + max(f[k-1, j] - prices[j]) { j in [0, i-1] } ) -) - -显然, f[0, i] = 0, f[k, 0] = 0 - -这个算法可以形象地描述一下, 在 k = 1 时, 我们每次要找的就是 i 之前的最低谷点作为这次交易的开始点 j, 而当 k > 1 时, -我们 i 之前就有可能已经进行过交易了, 这时我们在找开始点 j 时, 就要同时考虑 "直到 j 为止, k-1 次交易的最大收益" - "j 本身的值". 以此来找到一个最佳点 j - -在实现时, 假如用 Bottom-Up 递推, 那么只需要维护一个 vec[i], 因为每轮递推时只会考虑上一轮的数据, 我们可以复用这个 O(N) 的额外存储空间 -*/ -impl Solution { - pub fn max_profit(prices: Vec) -> i32 { - if prices.is_empty() { - return 0; - } - let max_trans = 2; - let mut cache = vec![0; prices.len()]; - for trans in 0..max_trans { - // best_by_in 维护了考虑前 N 次交易的最佳的买入点, 即 max(f[k-1, j] - prices[j]) { j in [0, i-1] } - let mut best_buy_in = cache[0] - prices[0]; - for i in 1..prices.len() { - // 复用 vec 前暂存一下前一次的计算结果 - let temp = cache[i]; - cache[i] = i32::max(cache[i - 1], best_buy_in + prices[i]); - // 更新 best_buy_in - best_buy_in = i32::max(best_buy_in, temp - prices[i]); - } - } - return *cache.last().unwrap(); - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_123() { - assert_eq!(Solution::max_profit(vec![3, 3, 5, 0, 0, 3, 1, 4]), 6); - } -} diff --git a/src/solution/s0124_binary_tree_maximum_path_sum.rs b/src/solution/s0124_binary_tree_maximum_path_sum.rs deleted file mode 100644 index e7c57b49..00000000 --- a/src/solution/s0124_binary_tree_maximum_path_sum.rs +++ /dev/null @@ -1,100 +0,0 @@ -/** - * [124] Binary Tree Maximum Path Sum - * - * Given a non-empty binary tree, find the maximum path sum. - * - * For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. - * - * Example 1: - * - * - * Input: [1,2,3] - * - * 1 - * / \ - * 2 3 - * - * Output: 6 - * - * - * Example 2: - * - * - * Input: [-10,9,20,null,null,15,7] - * - * -10 - * / \ - * 9 20 - * / \ - * 15 7 - * - * Output: 42 - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-maximum-path-sum/ -// discuss: https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -典型的动态规划, 我们求以 node_i 为 root 的最大和, 可以下推到求 root 的左右子树, 这里要注意, 路径是不能分叉的, 因此 -我们记 f[node] 为以 node 为根的最大和, 记 g[node] 为 node 为根, *最多连通一侧子树*的最大和 - -我们在递推时要用 g[node], f[node] 在递推过程中每次计算一下用于更新 max 即可 - -g[node_i] = node_i.val + max(g[node_i.left], g[node_i.right], 0) -f[node_i] = node_i.val + max(g[node_i.left], 0) + max(g[node_i.right], 0) - -显然, g[None] = 0 (None 即空子树), 最终计算到 g[root] 中止, f 的最大值会在计算过程中出现(注意 f[root] 不一定是最大值) - -每个 node 最大和只依赖与其左右子树的最大和, 因此 Top-down 需要 O(N) 的空间 -Bottom-up 只需要 O(1) 空间 (做后序遍历从叶节点向上递推即可) -*/ -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn max_path_sum(root: Option>>) -> i32 { - let mut max = i32::min_value(); - Solution::postorder(root.as_ref(), &mut max); - max - } - - fn postorder(root: Option<&Rc>>, max: &mut i32) -> i32 { - if let Some(node) = root { - let left = Solution::postorder(node.borrow().left.as_ref(), max); - let right = Solution::postorder(node.borrow().right.as_ref(), max); - *max = i32::max( - node.borrow().val + i32::max(left, 0) + i32::max(right, 0), - *max, - ); - node.borrow().val + i32::max(i32::max(left, right), 0) - } else { - 0 - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_124() { - assert_eq!(Solution::max_path_sum(tree![1, 2, 3]), 6); - assert_eq!( - Solution::max_path_sum(tree![-10, 9, 20, null, null, 15, 7]), - 42 - ); - assert_eq!( - Solution::max_path_sum(tree![5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1]), - 48 - ); - assert_eq!(Solution::max_path_sum(tree![-3]), -3); - } -} diff --git a/src/solution/s0125_valid_palindrome.rs b/src/solution/s0125_valid_palindrome.rs deleted file mode 100644 index 2f090b72..00000000 --- a/src/solution/s0125_valid_palindrome.rs +++ /dev/null @@ -1,72 +0,0 @@ -/** - * [125] Valid Palindrome - * - * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. - * - * Note: For the purpose of this problem, we define empty string as valid palindrome. - * - * Example 1: - * - * - * Input: "A man, a plan, a canal: Panama" - * Output: true - * - * - * Example 2: - * - * - * Input: "race a car" - * Output: false - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/valid-palindrome/ -// discuss: https://leetcode.com/problems/valid-palindrome/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn is_palindrome(s: String) -> bool { - if s.is_empty() { - return true; - } - let seq = s.chars().collect::>(); - let (mut i, mut j) = (0_usize, seq.len() - 1); - while i < j { - while i < seq.len() && !seq[i].is_ascii_alphanumeric() { - i += 1; - } - while j > 0 && !seq[j].is_ascii_alphanumeric() { - j -= 1; - } - if i >= j { - break; - } - if seq[i].to_ascii_lowercase() != seq[j].to_ascii_lowercase() { - return false; - } - i += 1; - j -= 1; - } - true - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_125() { - assert_eq!( - Solution::is_palindrome("A man, a plan, a canal: Panama".to_owned()), - true - ); - assert_eq!(Solution::is_palindrome("race a car".to_owned()), false); - assert_eq!(Solution::is_palindrome("0P".to_owned()), false); - } -} diff --git a/src/solution/s0126_word_ladder_ii.rs b/src/solution/s0126_word_ladder_ii.rs deleted file mode 100644 index 32169865..00000000 --- a/src/solution/s0126_word_ladder_ii.rs +++ /dev/null @@ -1,258 +0,0 @@ -/** - * [126] Word Ladder II - * - * Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: - * - *
    - * Only one letter can be changed at a time - * Each transformed word must exist in the word list. Note that beginWord is not a transformed word. - *
- * - * Note: - * - * - * Return an empty list if there is no such transformation sequence. - * All words have the same length. - * All words contain only lowercase alphabetic characters. - * You may assume no duplicates in the word list. - * You may assume beginWord and endWord are non-empty and are not the same. - * - * - * Example 1: - * - * - * Input: - * beginWord = "hit", - * endWord = "cog", - * wordList = ["hot","dot","dog","lot","log","cog"] - * - * Output: - * [ - * ["hit","hot","dot","dog","cog"], - * ["hit","hot","lot","log","cog"] - * ] - * - * - * Example 2: - * - * - * Input: - * beginWord = "hit" - * endWord = "cog" - * wordList = ["hot","dot","dog","lot","log"] - * - * Output: [] - * - * Explanation: The endWord "cog" is not in wordList, therefore no possible transformation. - * - * - * - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/word-ladder-ii/ -// discuss: https://leetcode.com/problems/word-ladder-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -假如 A 经过一个字符的变换能得到 B, 则认为 A 与 B 之间有通路, 转化为一个 BFS 找无权图最短路径的问题 - -实现时, 可以先把图构造出来, 复杂度 O(L*N^2) (L 是字符串长度), 也可以每次都回到数组里去找连通点, 时间复杂度不变 - -由于要记录所有的路径, 因此我们需要把每个点的可能前置节点都记录下来, 最后用一个 DFS 或 BFS 找出所有路径 - -暂时想不到更好的办法 -*/ - -use std::collections::HashSet; -use std::collections::VecDeque; -impl Solution { - pub fn find_ladders( - begin_word: String, - end_word: String, - word_list: Vec, - ) -> Vec> { - let mut res = Vec::new(); - let len = word_list.len(); - let target = word_list.iter().position(|s| s == &end_word); - if target.is_none() { - return res; - } - let target = target.unwrap(); - let mut deq = VecDeque::new(); - deq.push_back(target); - // paths record the distance & previous index, we use 'len' to represent empty prev - let mut paths: Vec<(i32, Vec)> = vec![(i32::max_value(), vec![]); len]; - paths[target].0 = 0; - let mut find_shortest = false; - let mut shortest = i32::max_value(); - let mut in_queue = HashSet::new(); - while let Some(i) = deq.pop_front() { - if Solution::connect(&begin_word, &word_list[i]) { - // complete the path using dfs - if paths[i].0 > shortest { - continue; - } - Solution::dfs(i, vec![begin_word.clone()], &word_list, &paths, &mut res); - shortest = paths[i].0; - find_shortest = true; - } - // we have found the shortest path, just drain all the nodes in deq - if find_shortest { - continue; - } - for j in 0..len { - if j == i { - continue; - } - if Solution::connect(&word_list[i], &word_list[j]) { - if paths[i].0 + 1 <= paths[j].0 { - let mut prev = &mut paths[j].1; - prev.push(i); - paths[j].0 = paths[i].0 + 1; - if !in_queue.contains(&j) { - deq.push_back(j); - in_queue.insert(j); - } - } - } - } - } - res - } - - fn dfs( - curr: usize, - mut path: Vec, - words: &Vec, - paths: &Vec<(i32, Vec)>, - res: &mut Vec>, - ) { - path.push(words[curr].clone()); - if paths[curr].1.is_empty() { - res.push(path); - return; - } - for &prev in paths[curr].1.iter() { - Solution::dfs(prev, path.clone(), words, paths, res); - } - } - - #[inline(always)] - fn connect(s1: &str, s2: &str) -> bool { - if s1.len() != s2.len() { - return false; - } - let mut iter1 = s1.chars().into_iter(); - let mut iter2 = s2.chars().into_iter(); - let mut diff = 0; - while let (Some(c1), Some(c2)) = (iter1.next(), iter2.next()) { - if c1 != c2 { - diff += 1; - if diff >= 2 { - return false; - } - } - } - true - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_126() { - assert_eq!( - Solution::find_ladders( - "hit".to_owned(), - "cog".to_owned(), - vec_string!["hot", "dot", "dog", "lot", "log", "cog"] - ), - vec![ - vec_string!["hit", "hot", "dot", "dog", "cog"], - vec_string!["hit", "hot", "lot", "log", "cog"], - ] - ); - assert_eq!( - Solution::find_ladders( - "cet".to_owned(), - "ism".to_owned(), - vec_string![ - "kid", "tag", "pup", "ail", "tun", "woo", "erg", "luz", "brr", "gay", "sip", - "kay", "per", "val", "mes", "ohs", "now", "boa", "cet", "pal", "bar", "die", - "war", "hay", "eco", "pub", "lob", "rue", "fry", "lit", "rex", "jan", "cot", - "bid", "ali", "pay", "col", "gum", "ger", "row", "won", "dan", "rum", "fad", - "tut", "sag", "yip", "sui", "ark", "has", "zip", "fez", "own", "ump", "dis", - "ads", "max", "jaw", "out", "btu", "ana", "gap", "cry", "led", "abe", "box", - "ore", "pig", "fie", "toy", "fat", "cal", "lie", "noh", "sew", "ono", "tam", - "flu", "mgm", "ply", "awe", "pry", "tit", "tie", "yet", "too", "tax", "jim", - "san", "pan", "map", "ski", "ova", "wed", "non", "wac", "nut", "why", "bye", - "lye", "oct", "old", "fin", "feb", "chi", "sap", "owl", "log", "tod", "dot", - "bow", "fob", "for", "joe", "ivy", "fan", "age", "fax", "hip", "jib", "mel", - "hus", "sob", "ifs", "tab", "ara", "dab", "jag", "jar", "arm", "lot", "tom", - "sax", "tex", "yum", "pei", "wen", "wry", "ire", "irk", "far", "mew", "wit", - "doe", "gas", "rte", "ian", "pot", "ask", "wag", "hag", "amy", "nag", "ron", - "soy", "gin", "don", "tug", "fay", "vic", "boo", "nam", "ave", "buy", "sop", - "but", "orb", "fen", "paw", "his", "sub", "bob", "yea", "oft", "inn", "rod", - "yam", "pew", "web", "hod", "hun", "gyp", "wei", "wis", "rob", "gad", "pie", - "mon", "dog", "bib", "rub", "ere", "dig", "era", "cat", "fox", "bee", "mod", - "day", "apr", "vie", "nev", "jam", "pam", "new", "aye", "ani", "and", "ibm", - "yap", "can", "pyx", "tar", "kin", "fog", "hum", "pip", "cup", "dye", "lyx", - "jog", "nun", "par", "wan", "fey", "bus", "oak", "bad", "ats", "set", "qom", - "vat", "eat", "pus", "rev", "axe", "ion", "six", "ila", "lao", "mom", "mas", - "pro", "few", "opt", "poe", "art", "ash", "oar", "cap", "lop", "may", "shy", - "rid", "bat", "sum", "rim", "fee", "bmw", "sky", "maj", "hue", "thy", "ava", - "rap", "den", "fla", "auk", "cox", "ibo", "hey", "saw", "vim", "sec", "ltd", - "you", "its", "tat", "dew", "eva", "tog", "ram", "let", "see", "zit", "maw", - "nix", "ate", "gig", "rep", "owe", "ind", "hog", "eve", "sam", "zoo", "any", - "dow", "cod", "bed", "vet", "ham", "sis", "hex", "via", "fir", "nod", "mao", - "aug", "mum", "hoe", "bah", "hal", "keg", "hew", "zed", "tow", "gog", "ass", - "dem", "who", "bet", "gos", "son", "ear", "spy", "kit", "boy", "due", "sen", - "oaf", "mix", "hep", "fur", "ada", "bin", "nil", "mia", "ewe", "hit", "fix", - "sad", "rib", "eye", "hop", "haw", "wax", "mid", "tad", "ken", "wad", "rye", - "pap", "bog", "gut", "ito", "woe", "our", "ado", "sin", "mad", "ray", "hon", - "roy", "dip", "hen", "iva", "lug", "asp", "hui", "yak", "bay", "poi", "yep", - "bun", "try", "lad", "elm", "nat", "wyo", "gym", "dug", "toe", "dee", "wig", - "sly", "rip", "geo", "cog", "pas", "zen", "odd", "nan", "lay", "pod", "fit", - "hem", "joy", "bum", "rio", "yon", "dec", "leg", "put", "sue", "dim", "pet", - "yaw", "nub", "bit", "bur", "sid", "sun", "oil", "red", "doc", "moe", "caw", - "eel", "dix", "cub", "end", "gem", "off", "yew", "hug", "pop", "tub", "sgt", - "lid", "pun", "ton", "sol", "din", "yup", "jab", "pea", "bug", "gag", "mil", - "jig", "hub", "low", "did", "tin", "get", "gte", "sox", "lei", "mig", "fig", - "lon", "use", "ban", "flo", "nov", "jut", "bag", "mir", "sty", "lap", "two", - "ins", "con", "ant", "net", "tux", "ode", "stu", "mug", "cad", "nap", "gun", - "fop", "tot", "sow", "sal", "sic", "ted", "wot", "del", "imp", "cob", "way", - "ann", "tan", "mci", "job", "wet", "ism", "err", "him", "all", "pad", "hah", - "hie", "aim", "ike", "jed", "ego", "mac", "baa", "min", "com", "ill", "was", - "cab", "ago", "ina", "big", "ilk", "gal", "tap", "duh", "ola", "ran", "lab", - "top", "gob", "hot", "ora", "tia", "kip", "han", "met", "hut", "she", "sac", - "fed", "goo", "tee", "ell", "not", "act", "gil", "rut", "ala", "ape", "rig", - "cid", "god", "duo", "lin", "aid", "gel", "awl", "lag", "elf", "liz", "ref", - "aha", "fib", "oho", "tho", "her", "nor", "ace", "adz", "fun", "ned", "coo", - "win", "tao", "coy", "van", "man", "pit", "guy", "foe", "hid", "mai", "sup", - "jay", "hob", "mow", "jot", "are", "pol", "arc", "lax", "aft", "alb", "len", - "air", "pug", "pox", "vow", "got", "meg", "zoe", "amp", "ale", "bud", "gee", - "pin", "dun", "pat", "ten", "mob" - ] - ), - vec![ - vec_string![ - "cet", "get", "gee", "gte", "ate", "ats", "its", "ito", "ibo", "ibm", "ism" - ], - vec_string![ - "cet", "cat", "can", "ian", "inn", "ins", "its", "ito", "ibo", "ibm", "ism" - ], - vec_string![ - "cet", "cot", "con", "ion", "inn", "ins", "its", "ito", "ibo", "ibm", "ism" - ], - ] - ); - } -} diff --git a/src/solution/s0127_word_ladder.rs b/src/solution/s0127_word_ladder.rs deleted file mode 100644 index a67465fa..00000000 --- a/src/solution/s0127_word_ladder.rs +++ /dev/null @@ -1,132 +0,0 @@ -/** - * [127] Word Ladder - * - * Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: - * - *
    - * Only one letter can be changed at a time. - * Each transformed word must exist in the word list. Note that beginWord is not a transformed word. - *
- * - * Note: - * - * - * Return 0 if there is no such transformation sequence. - * All words have the same length. - * All words contain only lowercase alphabetic characters. - * You may assume no duplicates in the word list. - * You may assume beginWord and endWord are non-empty and are not the same. - * - * - * Example 1: - * - * - * Input: - * beginWord = "hit", - * endWord = "cog", - * wordList = ["hot","dot","dog","lot","log","cog"] - * - * Output: 5 - * - * Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", - * return its length 5. - * - * - * Example 2: - * - * - * Input: - * beginWord = "hit" - * endWord = "cog" - * wordList = ["hot","dot","dog","lot","log"] - * - * Output: 0 - * - * Explanation: The endWord "cog" is not in wordList, therefore no possible transformation. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/word-ladder/ -// discuss: https://leetcode.com/problems/word-ladder/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::HashSet; -use std::collections::VecDeque; -impl Solution { - pub fn ladder_length(begin_word: String, end_word: String, word_list: Vec) -> i32 { - let len = word_list.len(); - let target = word_list.iter().position(|s| s == &end_word); - if target.is_none() { - return 0; - } - let target = target.unwrap(); - let mut deq = VecDeque::new(); - let mut distance = vec![0; len]; - let mut remain = (0..len).collect::>(); - deq.push_back(target); - remain.remove(&target); - while let Some(i) = deq.pop_front() { - if Solution::connect(&begin_word, &word_list[i]) { - return distance[i] + 2; - } - remain.retain(|&j| { - if Solution::connect(&word_list[i], &word_list[j]) { - distance[j] = distance[i] + 1; - deq.push_back(j); - false - } else { - true - } - }); - } - 0 - } - - #[inline(always)] - fn connect(s1: &str, s2: &str) -> bool { - if s1.len() != s2.len() { - return false; - } - let mut iter1 = s1.chars().into_iter(); - let mut iter2 = s2.chars().into_iter(); - let mut diff = 0; - while let (Some(c1), Some(c2)) = (iter1.next(), iter2.next()) { - if c1 != c2 { - diff += 1; - if diff >= 2 { - return false; - } - } - } - true - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_127() { - assert_eq!( - Solution::ladder_length( - "hit".to_owned(), - "cog".to_owned(), - vec_string!["hot", "dot", "dog", "lot", "log", "cog"] - ), - 5 - ); - assert_eq!( - Solution::ladder_length( - "hit".to_owned(), - "cog".to_owned(), - vec_string!["hot", "dot", "dog", "lot", "log"] - ), - 0 - ); - } -} diff --git a/src/solution/s0128_longest_consecutive_sequence.rs b/src/solution/s0128_longest_consecutive_sequence.rs deleted file mode 100644 index f0e0806f..00000000 --- a/src/solution/s0128_longest_consecutive_sequence.rs +++ /dev/null @@ -1,65 +0,0 @@ -/** - * [128] Longest Consecutive Sequence - * - * Given an unsorted array of integers, find the length of the longest consecutive elements sequence. - * - * Your algorithm should run in O(n) complexity. - * - * Example: - * - * - * Input: [100, 4, 200, 1, 3, 2] - * Output: 4 - * Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/longest-consecutive-sequence/ -// discuss: https://leetcode.com/problems/longest-consecutive-sequence/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -要找到连续子串, 基本策略就是对每个 num, 判断 num+1, num+2, num+3... 是否在数组中, 直到不再连续 - -工程里写的话用排序是最清晰可维护的(需求变了很好改), 排序之后查找 num+1 是否存在就只需要 O(1) 的复杂度了: -看下一个元素是不是 num+1 即可 - -但题目一定要求 O(N) 的解法, 只能想些奇怪的办法了, HashSet 也能达到 O(1) 的查找效率. 但假如对每个元素 -都做一遍, 最差就是 O(N^2) 了, 可以发现对于一个连续序列 1,2,3,4,5,6 我们从 1 开始查就能找到这个序列, -从 2,3,4,5,6 开始查都是在做重复计算, 因此对于一个 num, 假如 num-1 存在于 HashSet 中, 我们就不需要考虑 -它了, 因为它是一次重复的计算. -*/ -use std::collections::HashSet; -impl Solution { - pub fn longest_consecutive(nums: Vec) -> i32 { - let mut max = 0; - let nums = nums.into_iter().collect::>(); - for &num in nums.iter() { - if !nums.contains(&(num - 1)) { - let mut curr = num; - let mut curr_max = 1; - while nums.contains(&(curr + 1)) { - curr += 1; - curr_max += 1; - } - max = i32::max(curr_max, max); - } - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_128() { - assert_eq!(Solution::longest_consecutive(vec![100, 4, 200, 1, 3, 2]), 4) - } -} diff --git a/src/solution/s0129_sum_root_to_leaf_numbers.rs b/src/solution/s0129_sum_root_to_leaf_numbers.rs deleted file mode 100644 index 1e44fb68..00000000 --- a/src/solution/s0129_sum_root_to_leaf_numbers.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [129] Sum Root to Leaf Numbers - * - * Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. - * - * An example is the root-to-leaf path 1->2->3 which represents the number 123. - * - * Find the total sum of all root-to-leaf numbers. - * - * Note: A leaf is a node with no children. - * - * Example: - * - * - * Input: [1,2,3] - * 1 - * / \ - * 2 3 - * Output: 25 - * Explanation: - * The root-to-leaf path 1->2 represents the number 12. - * The root-to-leaf path 1->3 represents the number 13. - * Therefore, sum = 12 + 13 = 25. - * - * Example 2: - * - * - * Input: [4,9,0,5,1] - * 4 - * / \ - * 9 0 - * / \ - * 5 1 - * Output: 1026 - * Explanation: - * The root-to-leaf path 4->9->5 represents the number 495. - * The root-to-leaf path 4->9->1 represents the number 491. - * The root-to-leaf path 4->0 represents the number 40. - * Therefore, sum = 495 + 491 + 40 = 1026. - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/sum-root-to-leaf-numbers/ -// discuss: https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn sum_numbers(root: Option>>) -> i32 { - let mut sum = 0; - if root.is_none() { - return sum; - } - let mut deq = VecDeque::new(); - deq.push_back((root.clone(), 0)); - while let Some(item) = deq.pop_front() { - if let (Some(node), acc) = item { - let acc = acc * 10 + node.borrow().val; - if node.borrow().left.is_none() && node.borrow().right.is_none() { - sum += acc; - continue; - } - deq.push_back((node.borrow().left.clone(), acc)); - deq.push_back((node.borrow().right.clone(), acc)); - } - } - sum - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_129() { - assert_eq!(Solution::sum_numbers(tree![1, 2, 3]), 25); - assert_eq!(Solution::sum_numbers(tree![4, 9, 0, 5, 1]), 1026); - } -} diff --git a/src/solution/s0130_surrounded_regions.rs b/src/solution/s0130_surrounded_regions.rs deleted file mode 100644 index 411286b4..00000000 --- a/src/solution/s0130_surrounded_regions.rs +++ /dev/null @@ -1,221 +0,0 @@ -/** - * [130] Surrounded Regions - * - * Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. - * - * A region is captured by flipping all 'O's into 'X's in that surrounded region. - * - * Example: - * - * - * X X X X - * X O O X - * X X O X - * X O X X - * - * - * After running your function, the board should be: - * - * - * X X X X - * X X X X - * X X X X - * X O X X - * - * - * Explanation: - * - * Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/surrounded-regions/ -// discuss: https://leetcode.com/problems/surrounded-regions/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -从最外层开始, 基于为 'O' 的格子做 DFS, 将与边界连接的所有 'O' 标记为一个特殊 char, 最后将没有标记到的 'O' 全部标记为 'X' -*/ -impl Solution { - pub fn solve(board: &mut Vec>) { - if board.is_empty() || board[0].is_empty() { - return; - } - let (height, width) = (board.len(), board[0].len()); - // 遍历最外层的 4 条边 - for j in 0..width { - Solution::dfs(0, j, height, width, board); - Solution::dfs(height - 1, j, height, width, board); - } - for i in 1..height - 1 { - Solution::dfs(i, 0, height, width, board); - Solution::dfs(i, width - 1, height, width, board); - } - for k in 0..height * width { - board[k / width][k % width] = if board[k / width][k % width] == '_' { - 'O' - } else { - 'X' - } - } - } - - fn dfs(i: usize, j: usize, height: usize, width: usize, board: &mut Vec>) { - if board[i][j] == 'O' { - board[i][j] = '_'; - if i > 1 { - Solution::dfs(i - 1, j, height, width, board) - } - if j > 1 { - Solution::dfs(i, j - 1, height, width, board) - } - if i + 1 < height { - Solution::dfs(i + 1, j, height, width, board) - } - if j + 1 < width { - Solution::dfs(i, j + 1, height, width, board) - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_130() { - let mut matrix = vec![ - vec!['X', 'X', 'X', 'X'], - vec!['X', 'O', 'O', 'X'], - vec!['X', 'X', 'O', 'X'], - vec!['X', 'O', 'X', 'X'], - ]; - Solution::solve(&mut matrix); - assert_eq!( - matrix, - vec![ - vec!['X', 'X', 'X', 'X'], - vec!['X', 'X', 'X', 'X'], - vec!['X', 'X', 'X', 'X'], - vec!['X', 'O', 'X', 'X'], - ] - ); - - let mut matrix = vec![ - vec!['X', 'X', 'X', 'X'], - vec!['X', 'O', 'O', 'X'], - vec!['X', 'O', 'O', 'X'], - vec!['X', 'X', 'X', 'X'], - ]; - Solution::solve(&mut matrix); - assert_eq!( - matrix, - vec![ - vec!['X', 'X', 'X', 'X'], - vec!['X', 'X', 'X', 'X'], - vec!['X', 'X', 'X', 'X'], - vec!['X', 'X', 'X', 'X'], - ] - ); - - let mut matrix = vec![ - vec!['X', 'X', 'X', 'X'], - vec!['O', 'X', 'O', 'X'], - vec!['O', 'X', 'O', 'X'], - vec!['X', 'O', 'X', 'X'], - ]; - Solution::solve(&mut matrix); - assert_eq!( - matrix, - vec![ - vec!['X', 'X', 'X', 'X'], - vec!['O', 'X', 'X', 'X'], - vec!['O', 'X', 'X', 'X'], - vec!['X', 'O', 'X', 'X'], - ] - ); - - let mut matrix = vec![ - vec!['X', 'X', 'X', 'X', 'O', 'X'], - vec!['O', 'X', 'X', 'O', 'O', 'X'], - vec!['X', 'O', 'X', 'O', 'O', 'O'], - vec!['X', 'O', 'O', 'O', 'X', 'O'], - vec!['O', 'O', 'X', 'X', 'O', 'X'], - vec!['X', 'O', 'X', 'O', 'X', 'X'], - ]; - Solution::solve(&mut matrix); - assert_eq!( - matrix, - vec![ - vec!['X', 'X', 'X', 'X', 'O', 'X'], - vec!['O', 'X', 'X', 'O', 'O', 'X'], - vec!['X', 'O', 'X', 'O', 'O', 'O'], - vec!['X', 'O', 'O', 'O', 'X', 'O'], - vec!['O', 'O', 'X', 'X', 'X', 'X'], - vec!['X', 'O', 'X', 'O', 'X', 'X'], - ] - ); - - let mut matrix = vec![ - vec![ - 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X', - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'O', 'O', 'O', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X', - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'O', 'O', 'X', 'O', 'X', 'O', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X', - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'O', 'X', 'O', 'X', 'O', 'O', 'O', 'X', 'X', - 'X', 'X', 'X', 'X', - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'O', 'O', 'O', 'X', 'X', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X', - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X', - ], - ]; - Solution::solve(&mut matrix); - assert_eq!( - matrix, - vec![ - vec![ - 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X' - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'O', 'O', 'O', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X' - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'O', 'O', 'X', 'O', 'X', 'O', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X' - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'O', 'X', 'O', 'X', 'O', 'O', 'O', 'X', 'X', - 'X', 'X', 'X', 'X' - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'O', 'O', 'O', 'X', 'X', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X' - ], - vec![ - 'X', 'X', 'X', 'X', 'X', 'O', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', - 'X', 'X', 'X', 'X' - ] - ] - ); - } -} diff --git a/src/solution/s0131_palindrome_partitioning.rs b/src/solution/s0131_palindrome_partitioning.rs deleted file mode 100644 index 22a92dfd..00000000 --- a/src/solution/s0131_palindrome_partitioning.rs +++ /dev/null @@ -1,120 +0,0 @@ -/** - * [131] Palindrome Partitioning - * - * Given a string s, partition s such that every substring of the partition is a palindrome. - * - * Return all possible palindrome partitioning of s. - * - * Example: - * - * - * Input: "aab" - * Output: - * [ - * ["aa","b"], - * ["a","a","b"] - * ] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/palindrome-partitioning/ -// discuss: https://leetcode.com/problems/palindrome-partitioning/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -记 n 个字符的回文拆分方式是 f(n) 种, 则: - -f(n) = (0..n).iter().fold(0, |acc, i| { - if is_palindrome(s[i..n]) { acc + f(i-1) } else { acc } -}) - -按这种方式向上递推即可, 时间复杂度为 O(N^3), 空间复杂度 O(N), 显然, is_palindrome 这一步仍然有重复计算 - -is_palindrome(s[i..n]) = s[i] == s[n] && is_palindrome(s[i+1..n-1]) - -存储所有 i, n 的 is_palindrome 结果, 则可以优化 is_palindrome 的时间到 O(1) - -最后的复杂度: 时间 O(N^2), 空间 O(N^2) -*/ -impl Solution { - pub fn partition(s: String) -> Vec> { - let s = s.chars().collect::>(); - if s.is_empty() { - return Vec::new(); - } - let mut palindrome_cache = vec![vec![None; s.len()]; s.len()]; - let mut res: Vec>> = Vec::with_capacity(s.len()); - res.push(vec![vec![(0, 1)]]); - for n in 1..s.len() { - let mut curr: Vec> = Vec::new(); - for i in 0..n + 1 { - if Solution::is_palindrome(&mut palindrome_cache, &s, i, n) { - if i > 0 { - for vec in res[i - 1].iter() { - let mut new_vec = vec.clone(); - new_vec.push((i, n + 1)); - curr.push(new_vec); - } - } else { - curr.push(vec![(i, n + 1)]); - } - } - } - res.push(curr); - } - (*res[s.len() - 1]) - .into_iter() - .map(|vec| { - vec.iter() - .map(|&range| s[range.0..range.1].iter().collect::()) - .collect::>() - }) - .collect() - } - - fn is_palindrome( - cache: &mut Vec>>, - s: &Vec, - i: usize, - j: usize, - ) -> bool { - if j <= i { - return true; - } - if let Some(result) = cache[i][j] { - result - } else { - let result = s[i] == s[j] - && (i + 1 > s.len() || j < 1 || Solution::is_palindrome(cache, s, i + 1, j - 1)); - cache[i][j] = Some(result); - result - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_131() { - assert_eq!( - Solution::partition("aab".to_owned()), - vec![vec_string!["aa", "b"], vec_string!["a", "a", "b"],] - ); - assert_eq!( - Solution::partition("aaa".to_owned()), - vec![ - vec_string!["aaa"], - vec_string!["a", "aa"], - vec_string!["aa", "a"], - vec_string!["a", "a", "a"], - ] - ); - } -} diff --git a/src/solution/s0132_palindrome_partitioning_ii.rs b/src/solution/s0132_palindrome_partitioning_ii.rs deleted file mode 100644 index 81b75cf6..00000000 --- a/src/solution/s0132_palindrome_partitioning_ii.rs +++ /dev/null @@ -1,91 +0,0 @@ -/** - * [132] Palindrome Partitioning II - * - * Given a string s, partition s such that every substring of the partition is a palindrome. - * - * Return the minimum cuts needed for a palindrome partitioning of s. - * - * Example: - * - * - * Input: "aab" - * Output: 1 - * Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/palindrome-partitioning-ii/ -// discuss: https://leetcode.com/problems/palindrome-partitioning-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -为了方便讨论, 我们记 n 个字符的最少回文分段是 f(n), 则切分次数为 f(n)-1, 接下来递推 f(n): - -f(n) = min(f(n-i) + 1) { i in [0..n] and s[i..n] is palindrome } - -显然, f(1) 为 1, f(0) 为 0 - -判断 is_palindrome 也需要优化, 使用一个备忘录, 将判断回文的操作优化到 O(1): - -is_palindrome(s[i..n]) = s[i] == s[n] && is_palindrome(s[i+1..n-1]) - -最后的复杂度: 时间 O(N^2), 空间 O(N^2) -*/ -impl Solution { - pub fn min_cut(s: String) -> i32 { - let s = s.chars().collect::>(); - if s.is_empty() { - return 0; - } - let mut palindrome_cache: Vec>> = vec![vec![None; s.len()]; s.len()]; - let mut min = Vec::with_capacity(s.len() + 1); - min.push(0); - min.push(1); - for i in 1..s.len() { - let mut local_min = i32::max_value(); - for j in 0..i + 1 { - if Solution::is_palindrome(&mut palindrome_cache, &s, j, i) { - local_min = i32::min(1 + min[j], local_min); - } - } - min.push(local_min); - } - min[s.len()] - 1 - } - - fn is_palindrome( - cache: &mut Vec>>, - s: &Vec, - i: usize, - j: usize, - ) -> bool { - if j <= i { - return true; - } - if let Some(result) = cache[i][j] { - result - } else { - let result = s[i] == s[j] - && (i + 1 > s.len() || j < 1 || Solution::is_palindrome(cache, s, i + 1, j - 1)); - cache[i][j] = Some(result); - result - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_132() { - assert_eq!(Solution::min_cut("aab".to_owned()), 1); - assert_eq!(Solution::min_cut("aaa".to_owned()), 0); - assert_eq!(Solution::min_cut("aabb".to_owned()), 1); - } -} diff --git a/src/solution/s0134_gas_station.rs b/src/solution/s0134_gas_station.rs deleted file mode 100644 index 352990f9..00000000 --- a/src/solution/s0134_gas_station.rs +++ /dev/null @@ -1,77 +0,0 @@ -/** - * [134] Gas Station - * - * There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. - * - * You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. - * - * Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. - * - * Note: - * - * - * If there exists a solution, it is guaranteed to be unique. - * Both input arrays are non-empty and have the same length. - * Each element in the input arrays is a non-negative integer. - * - * - * Example 1: - * - * - * Input: - * gas = [1,2,3,4,5] - * cost = [3,4,5,1,2] - * - * Output: 3 - * - * Explanation: - * Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 - * Travel to station 4. Your tank = 4 - 1 + 5 = 8 - * Travel to station 0. Your tank = 8 - 2 + 1 = 7 - * Travel to station 1. Your tank = 7 - 3 + 2 = 6 - * Travel to station 2. Your tank = 6 - 4 + 3 = 5 - * Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. - * Therefore, return 3 as the starting index. - * - * - * Example 2: - * - * - * Input: - * gas = [2,3,4] - * cost = [3,4,3] - * - * Output: -1 - * - * Explanation: - * You can't start at station 0 or 1, as there is not enough gas to travel to the next station. - * Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 - * Travel to station 0. Your tank = 4 - 3 + 2 = 3 - * Travel to station 1. Your tank = 3 - 3 + 3 = 3 - * You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. - * Therefore, you can't travel around the circuit once no matter where you start. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/gas-station/ -// discuss: https://leetcode.com/problems/gas-station/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn can_complete_circuit(gas: Vec, cost: Vec) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_134() {} -} diff --git a/src/solution/s0135_candy.rs b/src/solution/s0135_candy.rs deleted file mode 100644 index debb29d0..00000000 --- a/src/solution/s0135_candy.rs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * [135] Candy - * - * There are N children standing in a line. Each child is assigned a rating value. - * - * You are giving candies to these children subjected to the following requirements: - * - * - * Each child must have at least one candy. - * Children with a higher rating get more candies than their neighbors. - * - * - * What is the minimum candies you must give? - * - * Example 1: - * - * - * Input: [1,0,2] - * Output: 5 - * Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. - * - * - * Example 2: - * - * - * Input: [1,2,2] - * Output: 4 - * Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. - * The third child gets 1 candy because it satisfies the above two conditions. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/candy/ -// discuss: https://leetcode.com/problems/candy/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn candy(ratings: Vec) -> i32 { - let mut from = 0; - let mut n = 1; - let mut last = 1; - let mut ascending = false; - for i in 1..ratings.len() { - if ratings[i] == ratings[i - 1] { - n += 1; - from = i; - ascending = false; - } else if ratings[i] >= ratings[i - 1] { - from = i; - ascending = true; - last += 1; - n += last; - } else { - if ascending { - last = 1; - from = i; - ascending = false; - } - n += (i - from + 1) as i32; - } - } - n - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_135() { - assert_eq!(Solution::candy(vec![3, 2, 1, 2, 3]), 11); - assert_eq!(Solution::candy(vec![2, 2, 1, 2, 2]), 7); - assert_eq!(Solution::candy(vec![1, 0, 2]), 5); - assert_eq!(Solution::candy(vec![1, 2, 2]), 4); - assert_eq!(Solution::candy(vec![1, 1, 1, 1, 1, 1]), 6); - assert_eq!(Solution::candy(vec![1, 2, 2, 2, 2, 2, 2, 0]), 10); - } -} diff --git a/src/solution/s0136_single_number.rs b/src/solution/s0136_single_number.rs deleted file mode 100644 index 580d1213..00000000 --- a/src/solution/s0136_single_number.rs +++ /dev/null @@ -1,48 +0,0 @@ -/** - * [136] Single Number - * - * Given a non-empty array of integers, every element appears twice except for one. Find that single one. - * - * Note: - * - * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? - * - * Example 1: - * - * - * Input: [2,2,1] - * Output: 1 - * - * - * Example 2: - * - * - * Input: [4,1,2,1,2] - * Output: 4 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/single-number/ -// discuss: https://leetcode.com/problems/single-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -impl Solution { - pub fn single_number(nums: Vec) -> i32 { - nums.iter().fold(0, |acc, &num| acc ^ num) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_136() { - assert_eq!(Solution::single_number(vec![2, 2, 1]), 1); - assert_eq!(Solution::single_number(vec![4, 1, 2, 1, 2]), 4); - } -} diff --git a/src/solution/s0137_single_number_ii.rs b/src/solution/s0137_single_number_ii.rs deleted file mode 100644 index 5e99cd84..00000000 --- a/src/solution/s0137_single_number_ii.rs +++ /dev/null @@ -1,94 +0,0 @@ -/** - * [137] Single Number II - * - * Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. - * - * Note: - * - * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? - * - * Example 1: - * - * - * Input: [2,2,3,2] - * Output: 3 - * - * - * Example 2: - * - * - * Input: [0,1,0,1,0,1,99] - * Output: 99 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/single-number-ii/ -// discuss: https://leetcode.com/problems/single-number-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -糅合了一下 https://leetcode.com/problems/single-number-ii/discuss/43296/An-General-Way-to-Handle-All-this-sort-of-questions. 和 https://leetcode.com/problems/single-number-ii/discuss/43294/Challenge-me-thx - -第一个链接给出了通用解法: 对于一个数出现 M 次其它数都出现了 K 的场景, 我们可以用位运算记录 K 种状态(作为一个计数器)来解 - -这题的真值表(3种状态使用2位): - -a b c/c a'b'/a'b' -0 0 1/0 0 1 /0 0 -0 1 1/0 1 0 /0 1 -1 0 1/0 0 0 /1 0 - -根据数电的知识, 要根据这个真值表写出逻辑表达式, 以输出端为 '1' 的结果为准, 将每行的输入变量写成 AND 形式, 其中为 0 的输入量需要取反, 再将这几个 AND 形式做 OR 即可 - -令 a' = 1, 则: - -a b c a' -0 1 1 1 ~a & b & c -1 0 0 1 a & ~b & ~c - -a' = (~a & b & c) | (a & ~b & ~c) - -同理: - -b' = (~a & b & ~c) | (~a & ~b & c) - -这个每轮计算的位次数达到 17 次, 可以再优化一下: - -对 b' 化简: b' = ~a & (b & ~c | ~b & c) = ~a & b ^ c - -但这时 a 仍然比较复杂, 我们可以考虑能否用每轮算出的 b' 来简化 a 的计算, 则: - -a (b) b' c a' b' -1 (0) 0 0 1 0 -0 (1) 0 1 1 0 - -重写一下就是 a' = (a & ~b' & ~c) | (~a & ~b' & c) = ~b' & (a & ~c | ~a & c) = ~b' & a ^ c - -这个就和最开始第二链接里给出的超简洁解法一致了 - -最后的话, a 或 b 为 1 都可以输出到 1 (目标数出现1次或出现2次), 输出 a | b 即可 -*/ -impl Solution { - pub fn single_number(nums: Vec) -> i32 { - let (mut a, mut b) = (0, 0); - for &num in nums.iter() { - b = !a & (b ^ num); - a = !b & (a ^ num); - } - return a | b; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_137() { - assert_eq!(Solution::single_number(vec![0, 0, 0, 1, 1, 1, 5]), 5); - } -} diff --git a/src/solution/s0139_word_break.rs b/src/solution/s0139_word_break.rs deleted file mode 100644 index ce9e2684..00000000 --- a/src/solution/s0139_word_break.rs +++ /dev/null @@ -1,93 +0,0 @@ -/** - * [139] Word Break - * - * Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. - * - * Note: - * - * - * The same word in the dictionary may be reused multiple times in the segmentation. - * You may assume the dictionary does not contain duplicate words. - * - * - * Example 1: - * - * - * Input: s = "leetcode", wordDict = ["leet", "code"] - * Output: true - * Explanation: Return true because "leetcode" can be segmented as "leet code". - * - * - * Example 2: - * - * - * Input: s = "applepenapple", wordDict = ["apple", "pen"] - * Output: true - * Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". - * Note that you are allowed to reuse a dictionary word. - * - * - * Example 3: - * - * - * Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] - * Output: false - * - * - */ -pub struct Solution {} - -/* -记 f[n] 表示从 0 开始长度为 n 的 substring 是否可以被组成,那么: - -f[n] = f[k] && (s[k..n] in dict) -f[0] = true - -DP 向上递推即可 - -BFS 也是可以的 -*/ - -// problem: https://leetcode.com/problems/word-break/ -// discuss: https://leetcode.com/problems/word-break/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::HashSet; -impl Solution { - pub fn word_break(s: String, word_dict: Vec) -> bool { - let word_dict = word_dict.into_iter().collect::>(); - let mut dp = vec![false; s.len() + 1]; - dp[0] = true; - for i in 1..s.len() + 1 { - for j in 0..s.len() { - if dp[j] && word_dict.contains(&s[j..i]) { - dp[i] = true; - } - } - } - dp[s.len()] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_139() { - assert_eq!( - Solution::word_break("leetcode".to_owned(), vec_string!["leet", "code"]), - true - ); - assert_eq!( - Solution::word_break( - "catsandog".to_owned(), - vec_string!["cats", "dog", "sand", "and", "cat"] - ), - false - ); - } -} diff --git a/src/solution/s0140_word_break_ii.rs b/src/solution/s0140_word_break_ii.rs deleted file mode 100644 index 68c1319e..00000000 --- a/src/solution/s0140_word_break_ii.rs +++ /dev/null @@ -1,72 +0,0 @@ -/** - * [140] Word Break II - * - * 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. - * - * Note: - * - * - * The same word in the dictionary may be reused multiple times in the segmentation. - * You may assume the dictionary does not contain duplicate words. - * - * - * Example 1: - * - * - * Input: - * s = "catsanddog" - * wordDict = ["cat", "cats", "and", "sand", "dog"] - * Output: - * [ - * "cats and dog", - * "cat sand dog" - * ] - * - * - * Example 2: - * - * - * Input: - * s = "pineapplepenapple" - * wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] - * Output: - * [ - * "pine apple pen apple", - * "pineapple pen apple", - * "pine applepen apple" - * ] - * Explanation: Note that you are allowed to reuse a dictionary word. - * - * - * Example 3: - * - * - * Input: - * s = "catsandog" - * wordDict = ["cats", "dog", "sand", "and", "cat"] - * Output: - * [] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/word-break-ii/ -// discuss: https://leetcode.com/problems/word-break-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn word_break(s: String, word_dict: Vec) -> Vec { - vec![] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_140() {} -} diff --git a/src/solution/s0143_reorder_list.rs b/src/solution/s0143_reorder_list.rs deleted file mode 100644 index 1a7854cc..00000000 --- a/src/solution/s0143_reorder_list.rs +++ /dev/null @@ -1,50 +0,0 @@ -/** - * [143] Reorder List - * - * Given a singly linked list L: L0→L1→…→Ln-1→Ln,
- * reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… - * - * You may not modify the values in the list's nodes, only nodes itself may be changed. - * - * Example 1: - * - * - * Given 1->2->3->4, reorder it to 1->4->2->3. - * - * Example 2: - * - * - * Given 1->2->3->4->5, reorder it to 1->5->2->4->3. - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/reorder-list/ -// discuss: https://leetcode.com/problems/reorder-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* - 1->2->3->4->5 - - 1->2->3<-4<-5 - - 1->5->2->4->3 -*/ -impl Solution { - pub fn reorder_list(head: &mut Option>) { - // TODO - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_143() {} -} diff --git a/src/solution/s0144_binary_tree_preorder_traversal.rs b/src/solution/s0144_binary_tree_preorder_traversal.rs deleted file mode 100644 index 3d823976..00000000 --- a/src/solution/s0144_binary_tree_preorder_traversal.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [144] Binary Tree Preorder Traversal - * - * Given a binary tree, return the preorder traversal of its nodes' values. - * - * Example: - * - * - * Input: [1,null,2,3] - * 1 - * \ - * 2 - * / - * 3 - * - * Output: [1,2,3] - * - * - * Follow up: Recursive solution is trivial, could you do it iteratively? - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-preorder-traversal/ -// discuss: https://leetcode.com/problems/binary-tree-preorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn preorder_traversal(root: Option>>) -> Vec { - let mut res = Vec::new(); - Solution::helper(root, &mut res); - res - } - - fn helper(root: Option>>, vec: &mut Vec) { - if let Some(node) = root { - vec.push(node.borrow().val); - Solution::helper(node.borrow().left.clone(), vec); - Solution::helper(node.borrow().right.clone(), vec); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_144() { - assert_eq!( - Solution::preorder_traversal(tree![1, null, 2, 3]), - vec![1, 2, 3] - ); - } -} diff --git a/src/solution/s0145_binary_tree_postorder_traversal.rs b/src/solution/s0145_binary_tree_postorder_traversal.rs deleted file mode 100644 index 63197e88..00000000 --- a/src/solution/s0145_binary_tree_postorder_traversal.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [145] Binary Tree Postorder Traversal - * - * Given a binary tree, return the postorder traversal of its nodes' values. - * - * Example: - * - * - * Input: [1,null,2,3] - * 1 - * \ - * 2 - * / - * 3 - * - * Output: [3,2,1] - * - * - * Follow up: Recursive solution is trivial, could you do it iteratively? - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-postorder-traversal/ -// discuss: https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn postorder_traversal(root: Option>>) -> Vec { - let mut res = Vec::new(); - Solution::helper(root, &mut res); - res - } - - fn helper(root: Option>>, vec: &mut Vec) { - if let Some(node) = root { - Solution::helper(node.borrow().left.clone(), vec); - Solution::helper(node.borrow().right.clone(), vec); - vec.push(node.borrow().val); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_145() { - assert_eq!( - Solution::postorder_traversal(tree![1, null, 2, 3]), - vec![3, 2, 1] - ); - } -} diff --git a/src/solution/s0146_lru_cache.rs b/src/solution/s0146_lru_cache.rs deleted file mode 100644 index 226cbf77..00000000 --- a/src/solution/s0146_lru_cache.rs +++ /dev/null @@ -1,200 +0,0 @@ -/** - * [146] LRU Cache - * - * - * Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. - * - * - * - * get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
- * put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. - * - * - * Follow up:
- * Could you do both operations in O(1) time complexity? - * - * Example: - * - * LRUCache cache = new LRUCache( 2 /* capacity */ ); - * - * cache.put(1, 1); - * cache.put(2, 2); - * cache.get(1); // returns 1 - * cache.put(3, 3); // evicts key 2 - * cache.get(2); // returns -1 (not found) - * cache.put(4, 4); // evicts key 1 - * cache.get(1); // returns -1 (not found) - * cache.get(3); // returns 3 - * cache.get(4); // returns 4 - * - * - */ -// problem: https://leetcode.com/problems/lru-cache/ -// discuss: https://leetcode.com/problems/lru-cache/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -Least Recently Used, 最近最少使用, 关键在于追踪每一个 entry 的 age, 每次淘汰最小的那一个 key - -假如淘汰逻辑要做到 O(1) 复杂度, 我们可以引入一个链表, 每次 touch 一个值时, 就删掉它重新 push_back, 而当达到容量要驱逐时, 则 pop_front - -Rust 的链表不支持根据引用删除任意元素,也没有 LinkedHashMap,需要自己实现一个 -*/ -use std::collections::HashMap; -use std::mem; -use std::ptr; - -// Entry is either a map entry and a link-list node -pub struct LRUEntry { - key: i32, - val: i32, - prev: *mut LRUEntry, - next: *mut LRUEntry, -} - -impl LRUEntry { - pub fn new(key: i32, val: i32) -> Self { - LRUEntry { - key: key, - val: val, - prev: ptr::null_mut(), - next: ptr::null_mut(), - } - } -} - -pub struct LRUCache { - map: HashMap>, - cap: usize, - - // head and tail is dummy node of the double-linked-list - head: *mut LRUEntry, - tail: *mut LRUEntry, -} - -impl LRUCache { - pub fn new(capacity: i32) -> Self { - let capacity = capacity as usize; - let map = HashMap::with_capacity(capacity); - let cache = LRUCache { - map: map, - cap: capacity, - head: unsafe { Box::into_raw(Box::new(mem::uninitialized::())) }, - tail: unsafe { Box::into_raw(Box::new(mem::uninitialized::())) }, - }; - unsafe { - (*cache.head).next = cache.tail; - (*cache.tail).prev = cache.head; - } - - cache - } - - pub fn get(&mut self, key: i32) -> i32 { - let (ptr, val) = match self.map.get_mut(&key) { - None => (None, None), - Some(entry) => { - let ptr: *mut LRUEntry = &mut **entry; - (Some(ptr), Some(unsafe { (*entry).val })) - } - }; - - if let Some(ptr) = ptr { - self.detach(ptr); - self.push(ptr); - } - val.unwrap_or(-1) - } - - pub fn put(&mut self, key: i32, value: i32) { - let ptr = self.map.get_mut(&key).map(|entry| { - let ptr: *mut LRUEntry = &mut **entry; - ptr - }); - - match ptr { - Some(ptr) => { - // key already exist, update it - unsafe { (*ptr).val = value }; - self.detach(ptr); - self.push(ptr); - } - None => { - // insert new key, cache is full, evict - if self.map.len() == self.cap { - let mut old_entry = self.pop().unwrap(); - old_entry.key = key; - old_entry.val = value; - self.push(&mut *old_entry); - self.map.insert(key, old_entry); - } else { - let mut new_entry = Box::new(LRUEntry::new(key, value)); - self.push(&mut *new_entry); - self.map.insert(key, new_entry); - } - } - } - } - - // pop() remove the entry from map, detach the entry from head of linked-list, and return it - fn pop(&mut self) -> Option> { - let next; - unsafe { next = (*self.head).next } - // list is empty - if next == self.tail { - return None; - } - let key = unsafe { (*next).key }; - let mut old_entry = self.map.remove(&key).unwrap(); - self.detach(&mut *old_entry); - Some(old_entry) - } - - // push() pushs an entry to the tail of linked-list - fn push(&mut self, entry: *mut LRUEntry) { - unsafe { - // prev <-> tail - // prev <-> entry <-> tail - (*entry).prev = (*self.tail).prev; - (*entry).next = self.tail; - (*self.tail).prev = entry; - (*(*entry).prev).next = entry; - } - } - - // detach() remove an entry from the linked-list - fn detach(&mut self, entry: *mut LRUEntry) { - unsafe { - // prev <-> entry <-> next - // prev <-> next - (*(*entry).prev).next = (*entry).next; - (*(*entry).next).prev = (*entry).prev; - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_146() { - println!("init cache"); - let mut lru_cache = LRUCache::new(2); - lru_cache.put(1, 1); - lru_cache.put(2, 2); - println!("return 1"); - assert_eq!(lru_cache.get(1), 1); // returns 1 - println!("evict key 2"); - lru_cache.put(3, 3); // evicts key 2 - println!("return -1"); - assert_eq!(lru_cache.get(2), -1); // returns -1 (not found) - lru_cache.put(4, 4); // evicts key 1 - assert_eq!(lru_cache.get(1), -1); // returns -1 (not found) - assert_eq!(lru_cache.get(3), 3); // returns 3 - assert_eq!(lru_cache.get(4), 4); // returns 4 - } -} diff --git a/src/solution/s0147_insertion_sort_list.rs b/src/solution/s0147_insertion_sort_list.rs deleted file mode 100644 index 09aff82b..00000000 --- a/src/solution/s0147_insertion_sort_list.rs +++ /dev/null @@ -1,64 +0,0 @@ -/** - * [147] Insertion Sort List - * - * Sort a linked list using insertion sort. - * - *
    - *
- * - *
- * A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
- * With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list

- * - * - *
    - *
- * - * Algorithm of Insertion Sort: - * - *
    - * Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. - * 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. - * It repeats until no input elements remain. - *
- * - *
- * Example 1: - * - * - * Input: 4->2->1->3 - * Output: 1->2->3->4 - * - * - * Example 2: - * - * - * Input: -1->5->3->4->0 - * Output: -1->0->3->4->5 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/insertion-sort-list/ -// discuss: https://leetcode.com/problems/insertion-sort-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO; boring -impl Solution { - pub fn insertion_sort_list(head: Option>) -> Option> { - None - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_147() {} -} diff --git a/src/solution/s0148_sort_list.rs b/src/solution/s0148_sort_list.rs deleted file mode 100644 index 78b7f08c..00000000 --- a/src/solution/s0148_sort_list.rs +++ /dev/null @@ -1,125 +0,0 @@ -/** - * [148] Sort List - * - * Sort a linked list in O(n log n) time using constant space complexity. - * - * Example 1: - * - * - * Input: 4->2->1->3 - * Output: 1->2->3->4 - * - * - * Example 2: - * - * - * Input: -1->5->3->4->0 - * Output: -1->0->3->4->5 - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/sort-list/ -// discuss: https://leetcode.com/problems/sort-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -堆排序需要额外空间, 不行 - -快排: - * 不行, 单链表要快排必须同时持有两个 mut 引用, 而 rust 里这是不可能的(不知道用 unsafe 行不行) - * 不用 rust 的话应该是可行的, Lomuto-partition, 用一个慢指针记录 no_lager_than 位置 - -归并,有点慢, 每次切分要遍历找到切分点, 而且递归栈深度 O(logN) 也不算严格的 O(1) 空间 - -Rust 标准库的 std::collections::LinkedList 都没有实现 sort() 你敢信... - -这题用 rust 解对我而言真的是 Hard 级而不是 Medium 级了... - -这里也是前置知识不足, GG 了解到链表的最佳排序方式确实就是 merge-sort -*/ -impl Solution { - pub fn sort_list(mut head: Option>) -> Option> { - let mut len = 0; - let mut ptr = head.as_ref(); - while let Some(node) = ptr { - len += 1; - ptr = node.next.as_ref(); - } - Solution::merge_sort(head, len) - } - - fn merge_sort(mut head: Option>, len: i32) -> Option> { - if len < 2 { - return head; - } - let mut next = head.as_mut(); - let mut i = 1; - while i < len / 2 { - next = next.unwrap().next.as_mut(); - i += 1; - } - let mut l2 = next.unwrap().next.take(); - let mut l1 = Solution::merge_sort(head, len / 2); - let mut l2 = Solution::merge_sort(l2, len - len / 2); - Solution::merge(l1, l2) - } - - fn merge( - mut l1: Option>, - mut l2: Option>, - ) -> Option> { - let mut dummy = Some(Box::new(ListNode::new(0))); - let mut next = dummy.as_mut(); - loop { - match (l1, l2) { - (Some(mut node1), Some(mut node2)) => { - let node = if node1.val > node2.val { - // give back ownership - l2 = node2.next.take(); - l1 = Some(node1); - node2 - } else { - l1 = node1.next.take(); - l2 = Some(node2); - node1 - }; - next.as_mut().unwrap().next = Some(node); - next = next.unwrap().next.as_mut(); - } - (Some(mut node1), None) => { - next.unwrap().next = Some(node1); - break; - } - (None, Some(mut node2)) => { - next.unwrap().next = Some(node2); - break; - } - (None, None) => break, - } - } - dummy.unwrap().next - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_148() { - assert_eq!( - Solution::sort_list(linked![4, 2, 1, 3]), - linked![1, 2, 3, 4] - ); - assert_eq!( - Solution::sort_list(linked![-1, 5, 3, 4, 0]), - linked![-1, 0, 3, 4, 5] - ); - assert_eq!(Solution::sort_list(linked![]), linked![]); - } -} diff --git a/src/solution/s0149_max_points_on_a_line.rs b/src/solution/s0149_max_points_on_a_line.rs deleted file mode 100644 index 31ea4c62..00000000 --- a/src/solution/s0149_max_points_on_a_line.rs +++ /dev/null @@ -1,178 +0,0 @@ -/** - * [149] Max Points on a Line - * - * Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. - * - * Example 1: - * - * - * Input: [[1,1],[2,2],[3,3]] - * Output: 3 - * Explanation: - * ^ - * | - * | o - * | o - * | o - * +-------------> - * 0 1 2 3 4 - * - * - * Example 2: - * - * - * Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] - * Output: 4 - * Explanation: - * ^ - * | - * | o - * | o o - * | o - * | o o - * +-------------------> - * 0 1 2 3 4 5 6 - * - * - */ -pub struct Solution {} -use crate::util::point::Point; - -// problem: https://leetcode.com/problems/max-points-on-a-line/ -// discuss: https://leetcode.com/problems/max-points-on-a-line/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -要回顾下高中数学:已知两点, 求解一般式: - - * Ax + By + C = 0 - * A = y2 - y1, B = x1 - x2, C = x2y1 - x1y2 - -有这个知识之后,化为一般式,做三层遍历就行,再加上一个 HashSet,避免对同一直线上点的重复计算,时间复杂度可以是 O(N^2) - -有两个坑要注意避免: - - * 给的 case 会导致 i32 溢出,这里直接用了 i64 表示 - * 给的 case 里有相同的点,直接处理相同点的话会导致最坏情况复杂度到 O(N^3),因此要先做一次转化,归并相同的点 - -用 Rust 实现有另一点注意的,给的 Point 没有实现 Hash Trait,要自己转化一下 -*/ -// straight-line expression: Ax + By + C = 0 -// A = y2 - y1, B = x1 - x2, C = x2y1 - x1y2 -#[derive(PartialEq, Hash, Eq, Debug)] -struct Line(i64, i64, i64); - -impl Line { - // Assumes that there is no same point - fn new(p1: &Point, p2: &Point) -> Self { - let x1 = p1.x as i64; - let x2 = p2.x as i64; - let y1 = p1.y as i64; - let y2 = p2.y as i64; - Line(y2 - y1, x1 - x2, x2 * y1 - x1 * y2) - } - fn contains(&self, p: &Point) -> bool { - self.0 * p.x as i64 + self.1 * p.y as i64 + self.2 == 0_i64 - } -} - -use std::collections::HashMap; -use std::collections::HashSet; -impl Solution { - pub fn max_points(points: Vec) -> i32 { - // fold same point, record the point count - let points: Vec<(Point, i32)> = points - .into_iter() - .fold(HashMap::new(), |mut map, v| { - *map.entry((v.x, v.y)).or_insert(0) += 1; - map - }) - .into_iter() - .map(|(k, v)| (Point::new(k.0, k.1), v)) // Point did not implement Hash trait - .collect(); - - // any two points in a straight-line, return quickly - if points.len() < 3 { - return points.into_iter().fold(0, |acc, v| acc + v.1); - } - let mut max = 2; - let mut set: HashSet = HashSet::new(); - for i in 0..(points.len() - 1) { - for j in i + 1..points.len() { - let line = Line::new(&points[i].0, &points[j].0); - if set.contains(&line) { - continue; - } - let mut curr = points[i].1 + points[j].1; - for k in j + 1..points.len() { - if line.contains(&points[k].0) { - curr += points[k].1; - } - } - max = i32::max(max, curr); - } - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_149() { - assert_eq!( - Solution::max_points(vec![point![1, 1], point![2, 2], point![3, 3]]), - 3 - ); - assert_eq!( - Solution::max_points(vec![ - point![1, 1], - point![3, 2], - point![5, 3], - point![4, 1], - point![2, 3], - point![1, 4] - ]), - 4 - ); - assert_eq!( - Solution::max_points(vec![point![0, 0], point![1, 65536], point![65536, 0]]), - 2 - ); - assert_eq!( - Solution::max_points(vec![point![1, 1], point![1, 1], point![1, 1]]), - 3 - ); - assert_eq!( - Solution::max_points(vec![ - point![0, 9], - point![138, 429], - point![115, 359], - point![115, 359], - point![-30, -102], - point![230, 709], - point![-150, -686], - point![-135, -613], - point![-60, -248], - point![-161, -481], - point![207, 639], - point![23, 79], - point![-230, -691], - point![-115, -341], - point![92, 289], - point![60, 336], - point![-105, -467], - point![135, 701], - point![-90, -394], - point![-184, -551], - point![150, 774] - ]), - 12 - ) - } -} diff --git a/src/solution/s0150_evaluate_reverse_polish_notation.rs b/src/solution/s0150_evaluate_reverse_polish_notation.rs deleted file mode 100644 index 048824dd..00000000 --- a/src/solution/s0150_evaluate_reverse_polish_notation.rs +++ /dev/null @@ -1,91 +0,0 @@ -/** - * [150] Evaluate Reverse Polish Notation - * - * Evaluate the value of an arithmetic expression in Reverse Polish Notation. - * - * Valid operators are +, -, *, /. Each operand may be an integer or another expression. - * - * Note: - * - * - * Division between two integers should truncate toward zero. - * The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation. - * - * - * Example 1: - * - * - * Input: ["2", "1", "+", "3", "*"] - * Output: 9 - * Explanation: ((2 + 1) * 3) = 9 - * - * - * Example 2: - * - * - * Input: ["4", "13", "5", "/", "+"] - * Output: 6 - * Explanation: (4 + (13 / 5)) = 6 - * - * - * Example 3: - * - * - * Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] - * Output: 22 - * Explanation: - * ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 - * = ((10 * (6 / (12 * -11))) + 17) + 5 - * = ((10 * (6 / -132)) + 17) + 5 - * = ((10 * 0) + 17) + 5 - * = (0 + 17) + 5 - * = 17 + 5 - * = 22 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/evaluate-reverse-polish-notation/ -// discuss: https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn eval_rpn(tokens: Vec) -> i32 { - let mut stack: Vec = Vec::new(); - for t in tokens.iter() { - if let Ok(num) = t.parse::() { - stack.push(num); - } else { - let right = stack.pop().unwrap(); - let left = stack.pop().unwrap(); - match (t as &str) { - "*" => stack.push(left * right), - "+" => stack.push(left + right), - "/" => stack.push(left / right), - "-" => stack.push(left - right), - _ => unreachable!(), - } - } - } - stack.pop().unwrap() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_150() { - assert_eq!( - Solution::eval_rpn(vec_string![ - "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" - ]), - 22 - ); - } -} diff --git a/src/solution/s0151_reverse_words_in_a_string.rs b/src/solution/s0151_reverse_words_in_a_string.rs deleted file mode 100644 index 627f0dd6..00000000 --- a/src/solution/s0151_reverse_words_in_a_string.rs +++ /dev/null @@ -1,93 +0,0 @@ -/** - * [151] Reverse Words in a String - * - * Given an input string, reverse the string word by word. - * - * - * - * Example 1: - * - * - * Input: "the sky is blue" - * Output: "blue is sky the" - * - * - * Example 2: - * - * - * Input: " hello world! " - * Output: "world! hello" - * Explanation: Your reversed string should not contain leading or trailing spaces. - * - * - * Example 3: - * - * - * Input: "a good example" - * Output: "example good a" - * Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. - * - * - * - * - * Note: - * - * - * A word is defined as a sequence of non-space characters. - * Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. - * You need to reduce multiple spaces between two words to a single space in the reversed string. - * - * - * - * - * Follow up: - * - * For C programmers, try to solve it in-place in O(1) extra space. - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/reverse-words-in-a-string/ -// discuss: https://leetcode.com/problems/reverse-words-in-a-string/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn reverse_words(mut s: String) -> String { - let mut seq = s.trim().chars().collect::>(); - seq.reverse(); - let mut start_idx = 0_usize; - let mut i = 0_usize; - while i < seq.len() { - if seq[i] == ' ' { - if i == start_idx { - seq.remove(i); - continue; - } - seq[start_idx..i].reverse(); - start_idx = i + 1; - } - i += 1; - } - seq[start_idx..].reverse(); - seq.into_iter().collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_151() { - assert_eq!( - Solution::reverse_words("the sky is blue".to_owned()), - "blue is sky the".to_owned() - ); - assert_eq!( - Solution::reverse_words(" hello world! ".to_owned()), - "world! hello".to_owned() - ); - } -} diff --git a/src/solution/s0152_maximum_product_subarray.rs b/src/solution/s0152_maximum_product_subarray.rs deleted file mode 100644 index b85b5ecb..00000000 --- a/src/solution/s0152_maximum_product_subarray.rs +++ /dev/null @@ -1,81 +0,0 @@ -/** - * [152] Maximum Product Subarray - * - * Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. - * - * Example 1: - * - * - * Input: [2,3,-2,4] - * Output: 6 - * Explanation: [2,3] has the largest product 6. - * - * - * Example 2: - * - * - * Input: [-2,0,-1] - * Output: 0 - * Explanation: The result cannot be 2, because [-2,-1] is not a subarray. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/maximum-product-subarray/ -// discuss: https://leetcode.com/problems/maximum-product-subarray/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -f[i], g[i] means the max positive value and max negative value for the sub-seq end with index i - -then we have: - -f[i], g[i] = if nums[i] == 0 { - 0, 0 -} else if nums[i] > 0 { - f[i-1] * nums[i], g[i-1] * nums[i] -} else if nums[i] < 0 { - g[i-1] * nums[i], f[i-1] * nums[i] -} -*/ - -impl Solution { - pub fn max_product(nums: Vec) -> i32 { - let mut max = nums[0]; - let mut neg_max = 0; - let mut pos_max = 0; - for num in nums.into_iter() { - if num == 0 { - neg_max = 0; - pos_max = 0; - max = i32::max(max, 0); - } else if num > 0 { - pos_max = i32::max(pos_max * num, num); - neg_max = neg_max * num; - } else { - let pos_pre = pos_max; - pos_max = neg_max * num; - neg_max = i32::min(pos_pre * num, num); - } - if pos_max != 0 { - max = i32::max(max, pos_max); - } - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_152() { - assert_eq!(Solution::max_product(vec![2, 3, -2, 4]), 6); - assert_eq!(Solution::max_product(vec![-2, 0, -1]), 0); - assert_eq!(Solution::max_product(vec![-4, -3, -2]), 12); - } -} diff --git a/src/solution/s0153_find_minimum_in_rotated_sorted_array.rs b/src/solution/s0153_find_minimum_in_rotated_sorted_array.rs deleted file mode 100644 index 03b7e7f1..00000000 --- a/src/solution/s0153_find_minimum_in_rotated_sorted_array.rs +++ /dev/null @@ -1,64 +0,0 @@ -/** - * [153] Find Minimum in Rotated Sorted Array - * - * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. - * - * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). - * - * Find the minimum element. - * - * You may assume no duplicate exists in the array. - * - * Example 1: - * - * - * Input: [3,4,5,1,2] - * Output: 1 - * - * - * Example 2: - * - * - * Input: [4,5,6,7,0,1,2] - * Output: 0 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ -// discuss: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn find_min(nums: Vec) -> i32 { - let mut size = nums.len(); - if size == 0 { - return -1; - } - let mut base = 0_usize; - while size > 1 { - let half = size / 2; - let mid = base + half; - if nums[mid] > nums[base] { - base = mid; - } - size -= half; - } - i32::min(nums[base], nums[(base + 1) % nums.len()]) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_153() { - assert_eq!(Solution::find_min(vec![4, 5, 6, 1, 2, 3]), 1); - assert_eq!(Solution::find_min(vec![4, 5, 6, 7, 0, 1, 2]), 0); - } -} diff --git a/src/solution/s0154_find_minimum_in_rotated_sorted_array_ii.rs b/src/solution/s0154_find_minimum_in_rotated_sorted_array_ii.rs deleted file mode 100644 index cdb23ac3..00000000 --- a/src/solution/s0154_find_minimum_in_rotated_sorted_array_ii.rs +++ /dev/null @@ -1,79 +0,0 @@ -/** - * [154] Find Minimum in Rotated Sorted Array II - * - * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. - * - * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). - * - * Find the minimum element. - * - * The array may contain duplicates. - * - * Example 1: - * - * - * Input: [1,3,5] - * Output: 1 - * - * Example 2: - * - * - * Input: [2,2,2,0,1] - * Output: 0 - * - * Note: - * - * - * This is a follow up problem to Find Minimum in Rotated Sorted Array. - * Would allow duplicates affect the run-time complexity? How and why? - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ -// discuss: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -针对无重复的做法, 只要二分搜索找折点即可: 假如 nums[mid] > nums[base] 那么转折点一定在右侧, 否则在左侧 - -但假如有重复, 就可能有 nums[mid] == nums[base], 这时就尴尬了, 无法确定转折点在左半部分还是右半部分 - -可以考虑一个数组, [1,1,1,1,1,1,1,0,1,1,1,1,1,1] 这个数组无论怎么去找 0, 时间复杂度无法低于 O(N) - -但假如不是这种极端情况, 那么二分搜索还是能优化的, 在 153 的基础上, 碰到相等就跳过即可 -*/ -impl Solution { - pub fn find_min(nums: Vec) -> i32 { - let mut lo = 0; - let mut hi = nums.len() - 1; - let mut mid = 0; - while lo < hi { - mid = lo + (hi - lo) / 2; - if (nums[mid] > nums[hi]) { - lo = mid + 1; - } else if (nums[mid] < nums[hi]) { - hi = mid; - } else { - hi -= 1; - } - } - return nums[lo]; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_154() { - assert_eq!(Solution::find_min(vec![1, 2, 2, 2, 2, 2]), 1); - assert_eq!(Solution::find_min(vec![1, 3, 3]), 1); - assert_eq!(Solution::find_min(vec![3, 1, 3, 3]), 1); - } -} diff --git a/src/solution/s0155_min_stack.rs b/src/solution/s0155_min_stack.rs deleted file mode 100644 index 99a96698..00000000 --- a/src/solution/s0155_min_stack.rs +++ /dev/null @@ -1,116 +0,0 @@ -/** - * [155] Min Stack - * - * - * Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. - * - * - * push(x) -- Push element x onto stack. - * - * - * pop() -- Removes the element on top of the stack. - * - * - * top() -- Get the top element. - * - * - * getMin() -- Retrieve the minimum element in the stack. - * - * - * - * - * Example:
- * - * MinStack minStack = new MinStack(); - * minStack.push(-2); - * minStack.push(0); - * minStack.push(-3); - * minStack.getMin(); --> Returns -3. - * minStack.pop(); - * minStack.top(); --> Returns 0. - * minStack.getMin(); --> Returns -2. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/min-stack/ -// discuss: https://leetcode.com/problems/min-stack/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -这题居然是 easy... 我怀疑人生了, getMin() 怎么能做到常数时间? Heap 也是 LogN 啊 - -看了最高票解之后...........天哪, 我可太菜了 - -核心思想是保证每次 pop 时都能以常数时间更新最小值, 这就需要在空间上以某种方式记录下来 - -那一种做法就是存储每个元素和最小值之间的差值, 这样 pop 的时候就能不断还原出原始值 - -另一种更直观的做法就是每次入栈 min 时, 都把前一个 min (当前第二小的数字) 放在它前面, 作为记录 -*/ -struct MinStack { - vec: Vec, - min: i32, -} - -impl MinStack { - /** initialize your data structure here. */ - pub fn new() -> Self { - MinStack { - vec: Vec::new(), - min: i32::max_value(), - } - } - - pub fn push(&mut self, x: i32) { - if x <= self.min { - self.vec.push(self.min); - self.min = x; - } - self.vec.push(x); - } - - pub fn pop(&mut self) { - if self.vec.pop().unwrap() == self.min { - self.min = self.vec.pop().unwrap(); - } - } - - pub fn top(&self) -> i32 { - *self.vec.last().unwrap() - } - - pub fn get_min(&self) -> i32 { - self.min - } -} - -/** - * Your MinStack object will be instantiated and called as such: - * let obj = MinStack::new(); - * obj.push(x); - * obj.pop(); - * let ret_3: i32 = obj.top(); - * let ret_4: i32 = obj.get_min(); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - pub fn test_155() { - let mut min_stack = MinStack::new(); - min_stack.push(-2); - min_stack.push(0); - min_stack.push(-3); - assert_eq!(min_stack.get_min(), -3); // --> Returns -3. - min_stack.pop(); - assert_eq!(min_stack.top(), 0); // --> Returns 0. - assert_eq!(min_stack.get_min(), -2); // --> Returns -2.[] - } -} diff --git a/src/solution/s0162_find_peak_element.rs b/src/solution/s0162_find_peak_element.rs deleted file mode 100644 index 3888b998..00000000 --- a/src/solution/s0162_find_peak_element.rs +++ /dev/null @@ -1,67 +0,0 @@ -/** - * [162] Find Peak Element - * - * A peak element is an element that is greater than its neighbors. - * - * Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. - * - * The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. - * - * You may imagine that nums[-1] = nums[n] = -∞. - * - * Example 1: - * - * - * Input: nums = [1,2,3,1] - * Output: 2 - * Explanation: 3 is a peak element and your function should return the index number 2. - * - * Example 2: - * - * - * Input: nums = [1,2,1,3,5,6,4] - * Output: 1 or 5 - * Explanation: Your function can return either index number 1 where the peak element is 2, - * or index number 5 where the peak element is 6. - * - * - * Note: - * - * Your solution should be in logarithmic complexity. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/find-peak-element/ -// discuss: https://leetcode.com/problems/find-peak-element/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn find_peak_element(nums: Vec) -> i32 { - let (mut lo, mut hi) = (0_usize, nums.len() - 1); - let mut mid = 0; - while lo < hi { - mid = (hi - lo) / 2 + lo; - if mid + 1 < nums.len() && nums[mid] < nums[mid + 1] { - lo = mid + 1; - } else { - hi = mid; - } - } - lo as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_162() { - assert_eq!(Solution::find_peak_element(vec![1, 2, 3, 1]), 2); - assert_eq!(Solution::find_peak_element(vec![1, 2, 1, 3, 5, 6, 4]), 5); - } -} diff --git a/src/solution/s0164_maximum_gap.rs b/src/solution/s0164_maximum_gap.rs deleted file mode 100644 index bd961db7..00000000 --- a/src/solution/s0164_maximum_gap.rs +++ /dev/null @@ -1,66 +0,0 @@ -/** - * [164] Maximum Gap - * - * Given an unsorted array, find the maximum difference between the successive elements in its sorted form. - * - * Return 0 if the array contains less than 2 elements. - * - * Example 1: - * - * - * Input: [3,6,9,1] - * Output: 3 - * Explanation: The sorted form of the array is [1,3,6,9], either - * (3,6) or (6,9) has the maximum difference 3. - * - * Example 2: - * - * - * Input: [10] - * Output: 0 - * Explanation: The array contains less than 2 elements, therefore return 0. - * - * Note: - * - * - * You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range. - * Try to solve it in linear time/space. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/maximum-gap/ -// discuss: https://leetcode.com/problems/maximum-gap/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -/* -想不出来, 一看解析居然是 Radix Sort 或 Bucket Sort, 我就 ??? 了... - -最佳算法是 Bucket Sort 吗? (桶大小取 max - min / len 那种), 看时间复杂度好像是这样 - -但假如整体排布非常稠密, 那么这个聪明的算法也就退化成了桶大小为 1 的桶排序 -*/ -impl Solution { - pub fn maximum_gap(nums: Vec) -> i32 { - let mut nums = nums; - nums.sort_unstable(); - let mut gap = 0; - for i in 1..nums.len() { - gap = i32::max(nums[i] - nums[i - 1], gap); - } - gap - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_164() { - assert_eq!(Solution::maximum_gap(vec![3, 6, 9, 1]), 3); - } -} diff --git a/src/solution/s0165_compare_version_numbers.rs b/src/solution/s0165_compare_version_numbers.rs deleted file mode 100644 index b53f1bbb..00000000 --- a/src/solution/s0165_compare_version_numbers.rs +++ /dev/null @@ -1,112 +0,0 @@ -/** - * [165] Compare Version Numbers - * - * Compare two version numbers version1 and version2.
- * If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0. - * - * You may assume that the version strings are non-empty and contain only digits and the . character. - * The . character does not represent a decimal point and is used to separate number sequences. - * For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. - * You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0. - * - * - * - * Example 1: - * - * Input: version1 = "0.1", version2 = "1.1" - * Output: -1 - * - * Example 2: - * - * Input: version1 = "1.0.1", version2 = "1" - * Output: 1 - * - * Example 3: - * - * Input: version1 = "7.5.2.4", version2 = "7.5.3" - * Output: -1 - * - * Example 4: - * - * Input: version1 = "1.01", version2 = "1.001" - * Output: 0 - * Explanation: Ignoring leading zeroes, both “01” and “001" represent the same number “1” - * - * Example 5: - * - * Input: version1 = "1.0", version2 = "1.0.0" - * Output: 0 - * Explanation: The first version number does not have a third level revision number, which means its third level revision number is default to "0" - * - * - * - * Note: - *
    - * Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes. - * Version strings do not start or end with dots, and they will not be two consecutive dots. - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/compare-version-numbers/ -// discuss: https://leetcode.com/problems/compare-version-numbers/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn compare_version(version1: String, version2: String) -> i32 { - let v1: Vec<&str> = version1.split('.').collect::>(); - let v2: Vec<&str> = version2.split('.').collect::>(); - let mut i = 0_usize; - while i < v1.len() && i < v2.len() { - let left = v1[i].parse::().unwrap(); - let right = v2[i].parse::().unwrap(); - if left > right { - return 1; - } else if left < right { - return -1; - } - i += 1; - } - while i < v1.len() { - if v1[i].parse::().unwrap() > 0 { - return 1; - } - i += 1; - } - while i < v2.len() { - if v2[i].parse::().unwrap() > 0 { - return -1; - } - i += 1; - } - return 0; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_165() { - assert_eq!( - Solution::compare_version("0.1".to_owned(), "1.1".to_owned()), - -1 - ); - assert_eq!( - Solution::compare_version("1.0.1".to_owned(), "1".to_owned()), - 1 - ); - assert_eq!( - Solution::compare_version("7.5.2.4".to_owned(), "7.5.3".to_owned()), - -1 - ); - assert_eq!( - Solution::compare_version("1.01".to_owned(), "1.0001".to_owned()), - 0 - ); - } -} diff --git a/src/solution/s0166_fraction_to_recurring_decimal.rs b/src/solution/s0166_fraction_to_recurring_decimal.rs deleted file mode 100644 index 4585738f..00000000 --- a/src/solution/s0166_fraction_to_recurring_decimal.rs +++ /dev/null @@ -1,51 +0,0 @@ -/** - * [166] Fraction to Recurring Decimal - * - * Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. - * - * If the fractional part is repeating, enclose the repeating part in parentheses. - * - * Example 1: - * - * - * Input: numerator = 1, denominator = 2 - * Output: "0.5" - * - * - * Example 2: - * - * - * Input: numerator = 2, denominator = 1 - * Output: "2" - * - * Example 3: - * - * - * Input: numerator = 2, denominator = 3 - * Output: "0.(6)" - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/fraction-to-recurring-decimal/ -// discuss: https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO -impl Solution { - pub fn fraction_to_decimal(numerator: i32, denominator: i32) -> String { - "".to_owned() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_166() {} -} diff --git a/src/solution/s0167_two_sum_ii_input_array_is_sorted.rs b/src/solution/s0167_two_sum_ii_input_array_is_sorted.rs deleted file mode 100644 index 58de2e86..00000000 --- a/src/solution/s0167_two_sum_ii_input_array_is_sorted.rs +++ /dev/null @@ -1,58 +0,0 @@ -/** - * [167] Two Sum II - Input array is sorted - * - * 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. - * - * 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. - * - * Note: - * - * - * Your returned answers (both index1 and index2) are not zero-based. - * You may assume that each input would have exactly one solution and you may not use the same element twice. - * - * - * Example: - * - * - * Input: numbers = [2,7,11,15], target = 9 - * Output: [1,2] - * Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ -// discuss: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn two_sum(numbers: Vec, target: i32) -> Vec { - let mut i = 0_usize; - let mut j = numbers.len() - 1; - while i < j { - let sum = numbers[i] + numbers[j]; - if sum > target { - j -= 1; - } else if sum < target { - i += 1; - } else { - break; - } - } - return vec![i as i32 + 1, j as i32 + 1]; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_167() { - assert_eq!(Solution::two_sum(vec![2, 7, 11, 15], 9), vec![1, 2]); - } -} diff --git a/src/solution/s0168_excel_sheet_column_title.rs b/src/solution/s0168_excel_sheet_column_title.rs deleted file mode 100644 index 5a9dc585..00000000 --- a/src/solution/s0168_excel_sheet_column_title.rs +++ /dev/null @@ -1,78 +0,0 @@ -/** - * [168] Excel Sheet Column Title - * - * Given a positive integer, return its corresponding column title as appear in an Excel sheet. - * - * For example: - * - * - * 1 -> A - * 2 -> B - * 3 -> C - * ... - * 26 -> Z - * 27 -> AA - * 28 -> AB - * ... - * - * - * Example 1: - * - * - * Input: 1 - * Output: "A" - * - * - * Example 2: - * - * - * Input: 28 - * Output: "AB" - * - * - * Example 3: - * - * - * Input: 701 - * Output: "ZY" - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/excel-sheet-column-title/ -// discuss: https://leetcode.com/problems/excel-sheet-column-title/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn convert_to_title(n: i32) -> String { - let base = 26; - let mut n = n; - let mut res = Vec::new(); - while n > 0 { - let mut code = (n % base) as u8; - n = n / base; - if code == 0 { - n -= 1; - code = base as u8; - }; - let alphabetic = (('A' as u8) + (code - 1_u8)) as char; - res.push(alphabetic); - } - res.reverse(); - res.into_iter().collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_168() { - assert_eq!(Solution::convert_to_title(28), "AB".to_owned()); - assert_eq!(Solution::convert_to_title(1), "A".to_owned()); - } -} diff --git a/src/solution/s0169_majority_element.rs b/src/solution/s0169_majority_element.rs deleted file mode 100644 index be59bea6..00000000 --- a/src/solution/s0169_majority_element.rs +++ /dev/null @@ -1,73 +0,0 @@ -/** - * [169] Majority Element - * - * Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. - * - * You may assume that the array is non-empty and the majority element always exist in the array. - * - * Example 1: - * - * - * Input: [3,2,3] - * Output: 3 - * - * Example 2: - * - * - * Input: [2,2,1,1,1,2,2] - * Output: 2 - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/majority-element/ -// discuss: https://leetcode.com/problems/majority-element/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -抄的题解:Boyer-Moore Voting Algorithm -自己只能想到 HashMap 和排序, 真是太鸡儿菜了... - -Boyer-Moore Voting Algorithm 的思路是假设当前值为主元素, 碰到当前值则 +1, 非当前值则 -1, 计数器一旦归零, -就取下一个数为主元素 - -最后留下的数一定主元素 - -证明也很简单, 假设我们从第 i 位开始选择了一个数 A, 并且这个数 A 保持到了循环终止, 那么: - -我们知道, 第 nums[i..n] 中, A 是主元素, nums[0..i] 中, 有一个数 B 出现了一半的次数 - -假如 A = B, 那么 A 出现了大于一半的次数, A 一定是主元素 - -假如 A != B, 且主元素不是 A, 那么 B 包括其他任何数在整个数组中出现的次数一定不到一半(因为 B 包括其他任何数 -在前半部分**至多**出现一半, 而在后半部分不到一半), 因此不存在主元素, 这与题目给定的"一定存在主元素"矛盾, 因此 -A 一定是主元素 -*/ - -impl Solution { - pub fn majority_element(nums: Vec) -> i32 { - let mut count = 0; - let mut candidate = 0; - for &num in nums.iter() { - if count == 0 { - candidate = num; - } - count += if num == candidate { 1 } else { -1 }; - } - candidate - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_169() { - assert_eq!(Solution::majority_element(vec![2, 2, 1, 1, 1, 2, 2]), 2); - } -} diff --git a/src/solution/s0171_excel_sheet_column_number.rs b/src/solution/s0171_excel_sheet_column_number.rs deleted file mode 100644 index 1b2f611f..00000000 --- a/src/solution/s0171_excel_sheet_column_number.rs +++ /dev/null @@ -1,62 +0,0 @@ -/** - * [171] Excel Sheet Column Number - * - * Given a column title as appear in an Excel sheet, return its corresponding column number. - * - * For example: - * - * - * A -> 1 - * B -> 2 - * C -> 3 - * ... - * Z -> 26 - * AA -> 27 - * AB -> 28 - * ... - * - * - * Example 1: - * - * - * Input: "A" - * Output: 1 - * - * - * Example 2: - * - * - * Input: "AB" - * Output: 28 - * - * - * Example 3: - * - * - * Input: "ZY" - * Output: 701 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/excel-sheet-column-number/ -// discuss: https://leetcode.com/problems/excel-sheet-column-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// TODO: boring -impl Solution { - pub fn title_to_number(s: String) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_171() {} -} diff --git a/src/solution/s0172_factorial_trailing_zeroes.rs b/src/solution/s0172_factorial_trailing_zeroes.rs deleted file mode 100644 index 9a54916d..00000000 --- a/src/solution/s0172_factorial_trailing_zeroes.rs +++ /dev/null @@ -1,55 +0,0 @@ -/** - * [172] Factorial Trailing Zeroes - * - * Given an integer n, return the number of trailing zeroes in n!. - * - * Example 1: - * - * - * Input: 3 - * Output: 0 - * Explanation: 3! = 6, no trailing zero. - * - * Example 2: - * - * - * Input: 5 - * Output: 1 - * Explanation: 5! = 120, one trailing zero. - * - * Note: Your solution should be in logarithmic time complexity. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/factorial-trailing-zeroes/ -// discuss: https://leetcode.com/problems/factorial-trailing-zeroes/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn trailing_zeroes(n: i32) -> i32 { - let mut five_count = 0; - let mut n = n; - while n > 0 { - n = n / 5; - five_count += n; - } - five_count - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_172() { - assert_eq!(Solution::trailing_zeroes(3), 0); - assert_eq!(Solution::trailing_zeroes(5), 1); - assert_eq!(Solution::trailing_zeroes(20), 4); - assert_eq!(Solution::trailing_zeroes(1808548329), 452137076); - } -} diff --git a/src/solution/s0173_binary_search_tree_iterator.rs b/src/solution/s0173_binary_search_tree_iterator.rs deleted file mode 100644 index b350600d..00000000 --- a/src/solution/s0173_binary_search_tree_iterator.rs +++ /dev/null @@ -1,116 +0,0 @@ -/** - * [173] Binary Search Tree Iterator - * - * Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. - * - * Calling next() will return the next smallest number in the BST. - * - * - * - * - * - * - * Example: - * - * - * - * - * BSTIterator iterator = new BSTIterator(root); - * iterator.next(); // return 3 - * iterator.next(); // return 7 - * iterator.hasNext(); // return true - * iterator.next(); // return 9 - * iterator.hasNext(); // return true - * iterator.next(); // return 15 - * iterator.hasNext(); // return true - * iterator.next(); // return 20 - * iterator.hasNext(); // return false - * - * - * - * - * Note: - * - * - * next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. - * You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called. - * - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; -use std::cell::RefCell; -use std::rc::Rc; - -// problem: https://leetcode.com/problems/binary-search-tree-iterator/ -// discuss: https://leetcode.com/problems/binary-search-tree-iterator/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -非递归中序遍历 -*/ -pub struct BSTIterator { - stack: Vec>>, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl BSTIterator { - pub fn new(root: Option>>) -> Self { - let mut node = root; - let mut stack = Vec::new(); - while let Some(inner) = node.clone() { - stack.push(inner.clone()); - node = node.unwrap().borrow().left.clone(); - } - BSTIterator { stack: stack } - } - - /** @return the next smallest number */ - pub fn next(&mut self) -> i32 { - let node = self.stack.pop().unwrap(); - let res = node.borrow().val; - let mut next = node.borrow().right.clone(); - while let Some(inner) = next.clone() { - self.stack.push(inner.clone()); - next = next.unwrap().borrow().left.clone(); - } - res - } - - /** @return whether we have a next smallest number */ - pub fn has_next(&self) -> bool { - !self.stack.is_empty() - } -} - -/** - * Your BSTIterator object will be instantiated and called as such: - * let obj = BSTIterator::new(root); - * let ret_1: i32 = obj.next(); - * let ret_2: bool = obj.has_next(); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_173() { - let mut iterator = BSTIterator::new(tree![7, 3, 15, null, null, 9, 20]); - assert_eq!(iterator.next(), 3); // return 3 - assert_eq!(iterator.next(), 7); // return 7 - assert_eq!(iterator.has_next(), true); // return true - assert_eq!(iterator.next(), 9); // return 9 - assert_eq!(iterator.has_next(), true); // return true - assert_eq!(iterator.next(), 15); // return 15 - assert_eq!(iterator.has_next(), true); // return true - assert_eq!(iterator.next(), 20); // return 20 - assert_eq!(iterator.has_next(), false); // return false - } -} diff --git a/src/solution/s0174_dungeon_game.rs b/src/solution/s0174_dungeon_game.rs deleted file mode 100644 index 23be4d97..00000000 --- a/src/solution/s0174_dungeon_game.rs +++ /dev/null @@ -1,115 +0,0 @@ -/** - * [174] Dungeon Game - * - * - * The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess. - * - * The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. - * - * Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers). - * - * In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. - * - * - * - * Write a function to determine the knight's minimum initial health so that he is able to rescue the princess. - * - * For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
-2 (K)-33
-5-101
1030-5 (P)
- * - * - * - * Note: - * - * - * The knight's health has no upper bound. - * Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/dungeon-game/ -// discuss: https://leetcode.com/problems/dungeon-game/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -DP, 即从每个格子出发到达终点所需的最小生命值为 hp[i][j] - -则显然, hp[M-1][N-1] = min(dungeon[M-1][N-1], 0) + 1; - -hp[i][j] = min(min(hp[i+1][j], hp[i][j+1]) - dungeon[i][j], 1); - -倒推到 hp[0][0] 即可 - -这里倒推很重要, 因为正推很难 dp(有后效性) - -其实可以优化成 O(M+N) 空间复杂度, 从斜对角线往后推就只需要保存一个小数组, 但是下面这样更简明 -*/ -impl Solution { - pub fn calculate_minimum_hp(dungeon: Vec>) -> i32 { - let (height, width) = (dungeon.len(), dungeon[0].len()); - // Using dummy row to simplify logic - let mut hp = vec![vec![i32::max_value(); width + 1]; height + 1]; - hp[height][width - 1] = 1; - hp[height - 1][width] = 1; - for i in (0..height).rev() { - for j in (0..width).rev() { - hp[i][j] = i32::max(i32::min(hp[i + 1][j], hp[i][j + 1]) - dungeon[i][j], 1); - } - } - hp[0][0] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_174() { - assert_eq!( - Solution::calculate_minimum_hp(vec![ - vec![-2, -3, 3], - vec![-5, -10, 1], - vec![10, 30, -5], - ]), - 7 - ); - assert_eq!( - Solution::calculate_minimum_hp(vec![vec![1, -4, 5, -99], vec![2, -2, -2, -1]]), - 3 - ); - } -} diff --git a/src/solution/s0179_largest_number.rs b/src/solution/s0179_largest_number.rs deleted file mode 100644 index 65348165..00000000 --- a/src/solution/s0179_largest_number.rs +++ /dev/null @@ -1,60 +0,0 @@ -/** - * [179] Largest Number - * - * Given a list of non negative integers, arrange them such that they form the largest number. - * - * Example 1: - * - * - * Input: [10,2] - * Output: "210" - * - * Example 2: - * - * - * Input: [3,30,34,5,9] - * Output: "9534330" - * - * - * Note: The result may be very large, so you need to return a string instead of an integer. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/largest-number/ -// discuss: https://leetcode.com/problems/largest-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn largest_number(nums: Vec) -> String { - let mut nums = nums - .into_iter() - .map(|num| num.to_string()) - .collect::>(); - nums.sort_unstable_by(|a, b| format!("{}{}", b, a).cmp(&format!("{}{}", a, b))); - if nums[0] == "0" { - return "0".to_owned(); - } - nums.iter().fold(String::new(), |mut s, num| { - s.push_str(num); - s - }) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_179() { - assert_eq!( - Solution::largest_number(vec![3, 30, 34, 5, 9]), - "9534330".to_owned() - ); - assert_eq!(Solution::largest_number(vec![121, 12]), "12121".to_owned()); - } -} diff --git a/src/solution/s0187_repeated_dna_sequences.rs b/src/solution/s0187_repeated_dna_sequences.rs deleted file mode 100644 index 9ceb86cb..00000000 --- a/src/solution/s0187_repeated_dna_sequences.rs +++ /dev/null @@ -1,100 +0,0 @@ -/** - * [187] Repeated DNA Sequences - * - * All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. - * - * Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. - * - * Example: - * - * - * Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" - * - * Output: ["AAAAACCCCC", "CCCCCAAAAA"] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/repeated-dna-sequences/ -// discuss: https://leetcode.com/problems/repeated-dna-sequences/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -首先想到直接长度为 10 的 sliding window 滑过去加一个 HashSet - -但这种方法在空间上和每次操作的耗时上都比较差, 可以转化为四进制或者二进制编码来考虑 - -A,C,G,T <-> [00, 01, 10, 11] - -那就简单很多了, 往后滑动一格不再需要调整整个 substring, 只需要移位, HashSet 也就存个 u32 即可 -*/ -use std::collections::HashSet; -impl Solution { - pub fn find_repeated_dna_sequences(s: String) -> Vec { - let mut seq_code: u32 = 0; - let mut set: HashSet = HashSet::new(); - let mut repeat: HashSet = HashSet::new(); - let mut count = 0; - for ch in s.chars() { - seq_code <<= 2; - match ch { - 'A' => seq_code |= 0_u32, - 'C' => seq_code |= 1_u32, - 'G' => seq_code |= 2_u32, - 'T' => seq_code |= 3_u32, - _ => unreachable!(), - } - // skip first 9 chars - if count < 9 { - count += 1; - continue; - } - // mask high 12-bits - seq_code &= 0b0000_0000_0000_1111_1111_1111_1111_1111; - if !set.insert(seq_code) { - repeat.insert(seq_code); - } - } - // bits code to seq string - repeat - .iter() - .map(|&code| { - let mut substr = String::new(); - let mut code = code; - for _ in 0..10 { - // take the first 2 bits each time - substr.push(match code & 0b0000_0000_0000_1100_0000_0000_0000_0000 { - 0b0000_0000_0000_0000_0000_0000_0000_0000 => 'A', - 0b0000_0000_0000_0100_0000_0000_0000_0000 => 'C', - 0b0000_0000_0000_1000_0000_0000_0000_0000 => 'G', - 0b0000_0000_0000_1100_0000_0000_0000_0000 => 'T', - _ => unreachable!(), - }); - code <<= 2; - } - substr - }) - .collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_187() { - assert_eq!( - Solution::find_repeated_dna_sequences("AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT".to_owned()), - vec_string!["AAAAACCCCC", "CCCCCAAAAA"] - ); - assert_eq!( - Solution::find_repeated_dna_sequences("GAGAGAGAGAGA".to_owned()), - vec_string!["GAGAGAGAGA"] - ); - } -} diff --git a/src/solution/s0188_best_time_to_buy_and_sell_stock_iv.rs b/src/solution/s0188_best_time_to_buy_and_sell_stock_iv.rs deleted file mode 100644 index e9c23319..00000000 --- a/src/solution/s0188_best_time_to_buy_and_sell_stock_iv.rs +++ /dev/null @@ -1,103 +0,0 @@ -/** - * [188] Best Time to Buy and Sell Stock IV - * - * Say you have an array for which the i^th element is the price of a given stock on day i. - * - * Design an algorithm to find the maximum profit. You may complete at most k transactions. - * - * Note:
- * You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). - * - * Example 1: - * - * - * Input: [2,4,1], k = 2 - * Output: 2 - * Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. - * - * - * Example 2: - * - * - * Input: [3,2,6,5,0,3], k = 2 - * Output: 7 - * Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. - * Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ -// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -已经在 #123 里解过了, 为了方便阅读直接把那题的分析拷贝到这里 - -先考虑只进行 1 次交易的情况, 我们求以 i *为售出点*, 只进行 1 次交易获得的最大利润, 那么: - -f[i] = if f[i-1] > 0 { f[i-1] } else { 0 } + prices[i] - prices[i-1] - -这很容易解, 解完之后找出 f 里的最大值即可, 但这不容易推广到 K 次交易的情况, 因为这时 f[i] 不代表到 i *为止*的最大利润, 无法作为单独的交易帮助递推 -(到 i 为止的含义是售出点可以在 [0,i] 之间) - -我们可以稍作改进, 变成求以 i 为结束点, 只进行 1 次交易获得的最大利润, 那么: - -f[i] = max( - f[i-1], - prices[i] - min(prices[j] { j in [0, i-1] }) -) - -这仍然是一个 O(N) 的解法, 因为 min(prices[j] { j in [0, i-1] }) 不需要遍历, 可以在递推过程中直接维护好 - -现在再推广到进行 K 次交易的情况, 那我们要求以 i 为结束点, 进行 k 次交易获得的最大利润, 这时有了变化, 我们可以在 j 之前再进行 K - 1 次交易: - -f[k, i] = max( - f[k, i-1], - prices[i] + max(f[k-1, j] - prices[j]) { j in [0, i-1] } ) -) - -显然, f[0, i] = 0, f[k, 0] = 0 - -这个算法可以形象地描述一下, 在 k = 1 时, 我们每次要找的就是 i 之前的最低谷点作为这次交易的开始点 j, 而当 k > 1 时, -我们 i 之前就有可能已经进行过交易了, 这时我们在找开始点 j 时, 就要同时考虑 "直到 j 为止, k-1 次交易的最大收益" - "j 本身的值". 以此来找到一个最佳点 j - -在实现时, 假如用 Bottom-Up 递推, 那么只需要维护一个 vec[i], 因为每轮递推时只会考虑上一轮的数据, 我们可以复用这个 O(N) 的额外存储空间 - -最后, 这题会给 k 非常大的 corner case, 实际上 k 大于 prices.len() / 2 后面就没有意义了, 可以 shortcut 掉(== 允许无穷次交易的场景), 下面写的比较糙, -直接限制了一下循环次数, 实际跑的时候运行时间会长一点 -*/ -impl Solution { - pub fn max_profit(k: i32, prices: Vec) -> i32 { - if prices.is_empty() { - return 0; - } - let max_trans = k as usize; - let mut cache = vec![0; prices.len()]; - for _ in 0..usize::min(max_trans, prices.len() / 2 + 1) { - // best_by_in 维护了考虑前 N 次交易的最佳的买入点, 即 max(f[k-1, j] - prices[j]) { j in [0, i-1] } - let mut best_buy_in = cache[0] - prices[0]; - for i in 1..prices.len() { - // 复用 vec 前暂存一下前一次的计算结果 - let temp = cache[i]; - cache[i] = i32::max(cache[i - 1], best_buy_in + prices[i]); - // 更新 best_buy_in - best_buy_in = i32::max(best_buy_in, temp - prices[i]); - } - } - return *cache.last().unwrap(); - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_188() { - assert_eq!(Solution::max_profit(2, vec![3, 2, 6, 5, 0, 3]), 7); - } -} diff --git a/src/solution/s0189_rotate_array.rs b/src/solution/s0189_rotate_array.rs deleted file mode 100644 index 1a4d2ab8..00000000 --- a/src/solution/s0189_rotate_array.rs +++ /dev/null @@ -1,79 +0,0 @@ -/** - * [189] Rotate Array - * - * Given an array, rotate the array to the right by k steps, where k is non-negative. - * - * Example 1: - * - * - * Input: [1,2,3,4,5,6,7] and k = 3 - * Output: [5,6,7,1,2,3,4] - * Explanation: - * rotate 1 steps to the right: [7,1,2,3,4,5,6] - * rotate 2 steps to the right: [6,7,1,2,3,4,5] - * rotate 3 steps to the right: [5,6,7,1,2,3,4] - * - * - * Example 2: - * - * - * Input: [-1,-100,3,99] and k = 2 - * Output: [3,99,-1,-100] - * Explanation: - * rotate 1 steps to the right: [99,-1,-100,3] - * rotate 2 steps to the right: [3,99,-1,-100] - * - * - * Note: - * - * - * Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. - * Could you do it in-place with O(1) extra space? - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/rotate-array/ -// discuss: https://leetcode.com/problems/rotate-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn rotate(nums: &mut Vec, k: i32) { - let offset = (k as usize) % nums.len(); - if offset == 0 { - return; - } - let mut idx = 0; - let mut num = nums[0]; - let mut start_idx = 0; - for _ in 0..nums.len() { - idx = (idx + offset) % nums.len(); - let temp = num; - num = nums[idx]; - nums[idx] = temp; - if idx == start_idx { - idx += 1; - start_idx = idx; - num = nums[idx]; - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_189() { - let mut nums = vec![1, 2, 3, 4, 5, 6, 7]; - Solution::rotate(&mut nums, 3); - assert_eq!(nums, vec![5, 6, 7, 1, 2, 3, 4]); - let mut nums = vec![1, 2, 3, 4, 5, 6]; - Solution::rotate(&mut nums, 2); - assert_eq!(nums, vec![5, 6, 1, 2, 3, 4]); - } -} diff --git a/src/solution/s0198_house_robber.rs b/src/solution/s0198_house_robber.rs deleted file mode 100644 index 446e63f1..00000000 --- a/src/solution/s0198_house_robber.rs +++ /dev/null @@ -1,68 +0,0 @@ -/** - * [198] House Robber - * - * 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. - * - * 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. - * - * Example 1: - * - * - * Input: [1,2,3,1] - * Output: 4 - * Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). - * Total amount you can rob = 1 + 3 = 4. - * - * Example 2: - * - * - * Input: [2,7,9,3,1] - * Output: 12 - * Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). - * Total amount you can rob = 2 + 9 + 1 = 12. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/house-robber/ -// discuss: https://leetcode.com/problems/house-robber/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -动态规划, 记抢到第 i 户为止的最大收益为 F[i], 则: - -i 有两种情况, 抢或不抢, 抢的话则最大收益是 F[i-2] + nums[i], -不抢则保持和前一次结束的收益一致, 等于 F[i-1], 于是: - -F[i] = i32::max(nums[i] + F[i-2], F[i-1]) - -观察到 F[i] 只依赖 F[i-1] 和 F[i-2], 可以用常数空间复杂度完成 -*/ -impl Solution { - pub fn rob(nums: Vec) -> i32 { - let mut former_max = 0; - let mut curr_max = 0; - for &num in nums.iter() { - let mut temp = curr_max; - curr_max = i32::max(former_max + num, curr_max); - former_max = temp; - } - curr_max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_198() { - assert_eq!(Solution::rob(vec![2, 7, 9, 3, 1]), 12); - assert_eq!(Solution::rob(vec![2, 7, 9, 10, 1]), 17); - assert_eq!(Solution::rob(vec![2, 1, 1, 2]), 4); - } -} diff --git a/src/solution/s0199_binary_tree_right_side_view.rs b/src/solution/s0199_binary_tree_right_side_view.rs deleted file mode 100644 index e07dc998..00000000 --- a/src/solution/s0199_binary_tree_right_side_view.rs +++ /dev/null @@ -1,68 +0,0 @@ -/** - * [199] Binary Tree Right Side View - * - * 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. - * - * Example: - * - * - * Input: [1,2,3,null,5,null,4] - * Output: [1, 3, 4] - * Explanation: - * - * 1 <--- - * / \ - * 2 3 <--- - * \ \ - * 5 4 <--- - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-right-side-view/ -// discuss: https://leetcode.com/problems/binary-tree-right-side-view/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::Rc; -impl Solution { - pub fn right_side_view(root: Option>>) -> Vec { - let mut res = Vec::new(); - let mut current_level = 0; - if root.is_none() { - return res; - } - let mut deq = VecDeque::new(); - deq.push_back((0, root.clone())); - res.push(root.as_ref().unwrap().borrow().val); - while !deq.is_empty() { - if let Some((level, Some(node))) = deq.pop_front() { - deq.push_back((level + 1, node.borrow().right.clone())); - deq.push_back((level + 1, node.borrow().left.clone())); - if level > current_level { - res.push(node.borrow().val); - current_level = level; - } - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_199() { - assert_eq!( - Solution::right_side_view(tree![1, 2, 3, null, 5, null, 4]), - vec![1, 3, 4] - ); - } -} diff --git a/src/solution/s0200_number_of_islands.rs b/src/solution/s0200_number_of_islands.rs deleted file mode 100644 index 262f0315..00000000 --- a/src/solution/s0200_number_of_islands.rs +++ /dev/null @@ -1,122 +0,0 @@ -/** - * [200] Number of Islands - * - * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. - * - * Example 1: - * - * - * Input: - * 11110 - * 11010 - * 11000 - * 00000 - * - * Output: 1 - * - * - * Example 2: - * - * - * Input: - * 11000 - * 11000 - * 00100 - * 00011 - * - * Output: 3 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/number-of-islands/ -// discuss: https://leetcode.com/problems/number-of-islands/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Union-Find Set -impl Solution { - pub fn num_islands(grid: Vec>) -> i32 { - if grid.is_empty() || grid[0].is_empty() { - return 0; - } - let (height, width) = (grid.len(), grid[0].len()); - let mut parent = vec![vec![(width, height); width]; height]; - for i in 0..height { - for j in 0..width { - if grid[i][j] != '1' { - continue; - } - parent[i][j] = (i, j); - if i > 0 && grid[i - 1][j] == '1' { - Solution::union(&mut parent, (i, j), (i - 1, j)); - } - if j > 0 && grid[i][j - 1] == '1' { - Solution::union(&mut parent, (i, j), (i, j - 1)); - } - } - } - let mut cnt = 0; - for i in 0..height { - for j in 0..width { - if parent[i][j] == (i, j) { - cnt += 1; - } - } - } - cnt - } - - fn get_parent(parent: &mut Vec>, p: (usize, usize)) -> (usize, usize) { - let mut child = p; - let mut p = p; - while parent[p.0][p.1] != p { - p = parent[p.0][p.1]; - } - // path compression, adjust all the node's parent to root along the path - while child != p { - let temp = parent[child.0][child.1]; - parent[child.0][child.1] = p; - child = temp; - } - p - } - - fn union(parent: &mut Vec>, p1: (usize, usize), p2: (usize, usize)) { - let p1 = Solution::get_parent(parent, p1); - let p2 = Solution::get_parent(parent, p2); - if p1 == p2 { - return; - } - parent[p1.0][p1.1] = p2 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_200() { - assert_eq!( - Solution::num_islands(vec![ - vec!['1', '1', '1', '1', '0',], - vec!['1', '1', '0', '1', '0',], - vec!['1', '1', '0', '0', '0',], - vec!['0', '0', '0', '0', '0',], - ]), - 1 - ); - assert_eq!( - Solution::num_islands(vec![ - vec!['1', '1', 'o', '1', '0',], - vec!['1', '1', '0', '1', '0',], - vec!['1', '1', '0', '0', '0',], - vec!['0', '0', '0', '1', '1',], - ]), - 3 - ); - } -} diff --git a/src/solution/s0201_bitwise_and_of_numbers_range.rs b/src/solution/s0201_bitwise_and_of_numbers_range.rs deleted file mode 100644 index 6c46e74f..00000000 --- a/src/solution/s0201_bitwise_and_of_numbers_range.rs +++ /dev/null @@ -1,58 +0,0 @@ -/** - * [201] Bitwise AND of Numbers Range - * - * Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. - * - * Example 1: - * - * - * Input: [5,7] - * Output: 4 - * - * - * Example 2: - * - * - * Input: [0,1] - * Output: 0 - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/bitwise-and-of-numbers-range/ -// discuss: https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// just find the highest bit 1 of m and n -impl Solution { - pub fn range_bitwise_and(m: i32, n: i32) -> i32 { - let mut m = m; - let mut n = n; - if m == 0 { - return 0; - } - let mut step = 1; - while m != n { - // shortcut - if m == 0 { - return 0; - } - m >>= 1; - n >>= 1; - step <<= 1; - } - return m * step; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_201() { - assert_eq!(Solution::range_bitwise_and(5, 7), 4); - } -} diff --git a/src/solution/s0202_happy_number.rs b/src/solution/s0202_happy_number.rs deleted file mode 100644 index 076f2736..00000000 --- a/src/solution/s0202_happy_number.rs +++ /dev/null @@ -1,68 +0,0 @@ -/** - * [202] Happy Number - * - * Write an algorithm to determine if a number is "happy". - * - * 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. - * - * Example: - * - * - * Input: 19 - * Output: true - * Explanation: - * 1^2 + 9^2 = 82 - * 8^2 + 2^2 = 68 - * 6^2 + 8^2 = 100 - * 1^2 + 0^2 + 0^2 = 1 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/happy-number/ -// discuss: https://leetcode.com/problems/happy-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::HashSet; -impl Solution { - pub fn is_happy(n: i32) -> bool { - let mut set = HashSet::new(); - let mut n = n; - loop { - set.insert(n); - let temp = Solution::next(n); - if temp == 1 { - return true; - } - if !set.insert(temp) { - return false; - } - n = temp - } - return false; - } - - fn next(n: i32) -> i32 { - let mut res = 0; - let mut n = n; - while n != 0 { - res += (n % 10).pow(2); - n = n / 10; - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_202() { - assert_eq!(Solution::is_happy(19), true); - assert_eq!(Solution::is_happy(235123), false); - } -} diff --git a/src/solution/s0203_remove_linked_list_elements.rs b/src/solution/s0203_remove_linked_list_elements.rs deleted file mode 100644 index 3e48d811..00000000 --- a/src/solution/s0203_remove_linked_list_elements.rs +++ /dev/null @@ -1,50 +0,0 @@ -/** - * [203] Remove Linked List Elements - * - * Remove all elements from a linked list of integers that have value val. - * - * Example: - * - * - * Input: 1->2->6->3->4->5->6, val = 6 - * Output: 1->2->3->4->5 - * - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/remove-linked-list-elements/ -// discuss: https://leetcode.com/problems/remove-linked-list-elements/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn remove_elements(mut head: Option>, val: i32) -> Option> { - let mut dummy = Some(Box::new(ListNode::new(0))); - let mut next = dummy.as_mut(); - while let Some(mut inner) = head { - head = inner.next.take(); - if inner.val != val { - next.as_mut().unwrap().next = Some(inner); - next = next.unwrap().next.as_mut(); - } - } - dummy.unwrap().next - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_203() { - assert_eq!( - Solution::remove_elements(linked![1, 2, 6, 3, 4, 5, 6], 6), - linked![1, 2, 3, 4, 5] - ); - } -} diff --git a/src/solution/s0204_count_primes.rs b/src/solution/s0204_count_primes.rs deleted file mode 100644 index d6f0f134..00000000 --- a/src/solution/s0204_count_primes.rs +++ /dev/null @@ -1,68 +0,0 @@ -/** - * [204] Count Primes - * - * Count the number of prime numbers less than a non-negative number, n. - * - * Example: - * - * - * Input: 10 - * Output: 4 - * Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/count-primes/ -// discuss: https://leetcode.com/problems/count-primes/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn count_primes(n: i32) -> i32 { - if n <= 2 { - return 0; - } - let mut is_prime = vec![true; n as usize]; - is_prime[0] = false; - is_prime[1] = false; - let mut i = 2; - while i * i < n { - if !is_prime[i as usize] { - i += 1; - continue; - } - let mut j = i * i; - while j < n { - is_prime[j as usize] = false; - j += i; - } - i += 1; - } - let mut count = 0; - for &v in is_prime.iter() { - if v { - count += 1 - } - } - count - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_204() { - assert_eq!(Solution::count_primes(10), 4); - assert_eq!(Solution::count_primes(2), 0); - assert_eq!(Solution::count_primes(3), 1); - assert_eq!(Solution::count_primes(5), 2); - assert_eq!(Solution::count_primes(1), 0); - assert_eq!(Solution::count_primes(120), 30); - } -} diff --git a/src/solution/s0205_isomorphic_strings.rs b/src/solution/s0205_isomorphic_strings.rs deleted file mode 100644 index df697ebb..00000000 --- a/src/solution/s0205_isomorphic_strings.rs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * [205] Isomorphic Strings - * - * Given two strings s and t, determine if they are isomorphic. - * - * Two strings are isomorphic if the characters in s can be replaced to get t. - * - * All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. - * - * Example 1: - * - * - * Input: s = "egg", t = "add" - * Output: true - * - * - * Example 2: - * - * - * Input: s = "foo", t = "bar" - * Output: false - * - * Example 3: - * - * - * Input: s = "paper", t = "title" - * Output: true - * - * Note:
- * You may assume both s and t have the same length. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/isomorphic-strings/ -// discuss: https://leetcode.com/problems/isomorphic-strings/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::char; -use std::collections::hash_map::Entry; -use std::collections::HashMap; -impl Solution { - pub fn is_isomorphic(s: String, t: String) -> bool { - Solution::code(s) == Solution::code(t) - } - - fn code(s: String) -> String { - let mut map = HashMap::new(); - let mut start: char = '0'; - let mut res = String::new(); - for ch in s.chars() { - let v = map.entry(ch).or_insert_with(|| { - start = ((start as u8) + 1) as char; - start - }); - res.push(*v) - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_205() { - assert_eq!( - Solution::is_isomorphic("egg".to_owned(), "app".to_owned()), - true - ); - assert_eq!( - Solution::is_isomorphic("pecil".to_owned(), "this".to_owned()), - false - ); - assert_eq!( - Solution::is_isomorphic("paper".to_owned(), "title".to_owned()), - true - ); - } -} diff --git a/src/solution/s0206_reverse_linked_list.rs b/src/solution/s0206_reverse_linked_list.rs deleted file mode 100644 index b62aced8..00000000 --- a/src/solution/s0206_reverse_linked_list.rs +++ /dev/null @@ -1,52 +0,0 @@ -/** - * [206] Reverse Linked List - * - * Reverse a singly linked list. - * - * Example: - * - * - * Input: 1->2->3->4->5->NULL - * Output: 5->4->3->2->1->NULL - * - * - * Follow up: - * - * A linked list can be reversed either iteratively or recursively. Could you implement both? - * - */ -pub struct Solution {} -use crate::util::linked_list::{to_list, ListNode}; - -// problem: https://leetcode.com/problems/reverse-linked-list/ -// discuss: https://leetcode.com/problems/reverse-linked-list/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn reverse_list(head: Option>) -> Option> { - let mut curr = head; - let mut next = None; - while let Some(mut inner) = curr { - curr = inner.next.take(); - inner.next = next; - next = Some(inner); - } - next - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_206() { - assert_eq!( - Solution::reverse_list(linked![1, 2, 3, 4, 5]), - linked![5, 4, 3, 2, 1] - ); - } -} diff --git a/src/solution/s0207_course_schedule.rs b/src/solution/s0207_course_schedule.rs deleted file mode 100644 index 2a793683..00000000 --- a/src/solution/s0207_course_schedule.rs +++ /dev/null @@ -1,105 +0,0 @@ -/** - * [207] Course Schedule - * - * There are a total of n courses you have to take, labeled from 0 to n-1. - * - * Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] - * - * Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? - * - * Example 1: - * - * - * Input: 2, [[1,0]] - * Output: true - * Explanation: There are a total of 2 courses to take. - * To take course 1 you should have finished course 0. So it is possible. - * - * Example 2: - * - * - * Input: 2, [[1,0],[0,1]] - * Output: false - * Explanation: There are a total of 2 courses to take. - * To take course 1 you should have finished course 0, and to take course 0 you should - * also have finished course 1. So it is impossible. - * - * - * Note: - * - *
    - * The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. - * You may assume that there are no duplicate edges in the input prerequisites. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/course-schedule/ -// discuss: https://leetcode.com/problems/course-schedule/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// topology sort, BFS -use std::collections::VecDeque; -impl Solution { - pub fn can_finish(num_courses: i32, prerequisites: Vec>) -> bool { - let num = num_courses as usize; - let mut matrix = vec![vec![false; num]; num]; - let mut in_degree = vec![0; num]; - // collects node in degree - for pre in prerequisites.iter() { - if !matrix[pre[1] as usize][pre[0] as usize] { - in_degree[pre[0] as usize] += 1; - } - matrix[pre[1] as usize][pre[0] as usize] = true; - } - let mut deq = VecDeque::new(); - // BFS starts with nodes with 0 in degree - for (node, &v) in in_degree.iter().enumerate() { - if v == 0 { - deq.push_back(node); - } - } - let mut cnt = 0; - while let Some(node) = deq.pop_front() { - cnt += 1; - for (i, &connect) in matrix[node].iter().enumerate() { - if connect { - in_degree[i] -= 1; - if in_degree[i] == 0 { - deq.push_back(i); - } - } - } - } - cnt == num_courses - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_207() { - assert_eq!(Solution::can_finish(2, vec![vec![1, 0]]), true); - assert_eq!(Solution::can_finish(2, vec![vec![1, 0], vec![0, 1]]), false); - assert_eq!( - Solution::can_finish( - 8, - vec![ - vec![1, 0], - vec![2, 6], - vec![1, 7], - vec![6, 4], - vec![7, 0], - vec![0, 5] - ] - ), - true - ); - } -} diff --git a/src/solution/s0208_implement_trie_prefix_tree.rs b/src/solution/s0208_implement_trie_prefix_tree.rs deleted file mode 100644 index 9ac8e470..00000000 --- a/src/solution/s0208_implement_trie_prefix_tree.rs +++ /dev/null @@ -1,95 +0,0 @@ -/** - * [208] Implement Trie (Prefix Tree) - * - * Implement a trie with insert, search, and startsWith methods. - * - * Example: - * - * - * Trie trie = new Trie(); - * - * trie.insert("apple"); - * trie.search("apple"); // returns true - * trie.search("app"); // returns false - * trie.startsWith("app"); // returns true - * trie.insert("app"); - * trie.search("app"); // returns true - * - * - * Note: - * - * - * You may assume that all inputs are consist of lowercase letters a-z. - * All inputs are guaranteed to be non-empty strings. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/implement-trie-prefix-tree/ -// discuss: https://leetcode.com/problems/implement-trie-prefix-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -#[derive(Default)] -struct Trie { - is_end: bool, - nodes: [Option>; 26], -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl Trie { - /** Initialize your data structure here. */ - fn new() -> Self { - Default::default() - } - - /** insert a word into the trie. */ - fn insert(&mut self, word: String) { - let mut curr = self; - - for i in word.chars().map(|ch| (ch as u8 - 'a' as u8) as usize) { - curr = curr.nodes[i].get_or_insert_with(|| Box::new(Trie::new())); - } - curr.is_end = true; - } - - /** Returns if the word is in the trie. */ - fn search(&self, word: String) -> bool { - self.find(word).map_or(false, |t| t.is_end) - } - - /** Returns if there is any word in the trie that starts with the given prefix. */ - fn starts_with(&self, prefix: String) -> bool { - self.find(prefix).is_some() - } - - fn find(&self, word: String) -> Option<&Trie> { - let mut curr = self; - for i in word.chars().map(|ch| (ch as u8 - 'a' as u8) as usize) { - curr = curr.nodes[i].as_ref()?; - } - Some(curr) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_208() { - let mut trie = Trie::new(); - trie.insert("apple".to_owned()); - assert_eq!(trie.search("apple".to_owned()), true); // returns true - assert_eq!(trie.search("app".to_owned()), false); - assert_eq!(trie.starts_with("app".to_owned()), true); // returns true - trie.insert("app".to_owned()); - assert_eq!(trie.search("app".to_owned()), true); // returns true - } -} diff --git a/src/solution/s0209_minimum_size_subarray_sum.rs b/src/solution/s0209_minimum_size_subarray_sum.rs deleted file mode 100644 index b6a692d7..00000000 --- a/src/solution/s0209_minimum_size_subarray_sum.rs +++ /dev/null @@ -1,65 +0,0 @@ -/** - * [209] Minimum Size Subarray Sum - * - * 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. - * - * Example: - * - * - * Input: s = 7, nums = [2,3,1,2,4,3] - * Output: 2 - * Explanation: the subarray [4,3] has the minimal length under the problem constraint. - * - *
Follow up:
- * - *
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/minimum-size-subarray-sum/ -// discuss: https://leetcode.com/problems/minimum-size-subarray-sum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn min_sub_array_len(s: i32, nums: Vec) -> i32 { - let (mut i, mut j) = (0_usize, 0_usize); - let mut min = i32::max_value(); - let mut found = false; - let mut sum = 0; - while j < nums.len() { - sum += nums[j]; - if sum >= s { - found = true; - while i <= j { - sum -= nums[i]; - i += 1; - if sum < s { - min = i32::min(min, j as i32 - i as i32 + 2); - break; - } - } - } - j += 1; - } - if found { - min - } else { - 0 - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_209() { - assert_eq!(Solution::min_sub_array_len(7, vec![2, 3, 1, 2, 4, 3]), 2); - assert_eq!(Solution::min_sub_array_len(4, vec![1, 4, 4]), 1); - } -} diff --git a/src/solution/s0210_course_schedule_ii.rs b/src/solution/s0210_course_schedule_ii.rs deleted file mode 100644 index dd3a1b03..00000000 --- a/src/solution/s0210_course_schedule_ii.rs +++ /dev/null @@ -1,98 +0,0 @@ -/** - * [210] Course Schedule II - * - * There are a total of n courses you have to take, labeled from 0 to n-1. - * - * Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] - * - * Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses. - * - * There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array. - * - * Example 1: - * - * - * Input: 2, [[1,0]] - * Output: [0,1] - * Explanation: There are a total of 2 courses to take. To take course 1 you should have finished - * course 0. So the correct course order is [0,1] . - * - * Example 2: - * - * - * Input: 4, [[1,0],[2,0],[3,1],[3,2]] - * Output: [0,1,2,3] or [0,2,1,3] - * Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both - * courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. - * So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] . - * - * Note: - * - *
    - * The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. - * You may assume that there are no duplicate edges in the input prerequisites. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/course-schedule-ii/ -// discuss: https://leetcode.com/problems/course-schedule-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::VecDeque; -impl Solution { - pub fn find_order(num_courses: i32, prerequisites: Vec>) -> Vec { - let num = num_courses as usize; - let mut matrix = vec![vec![false; num]; num]; - let mut in_degree = vec![0; num]; - // collects node in degree - for pre in prerequisites.iter() { - if !matrix[pre[1] as usize][pre[0] as usize] { - in_degree[pre[0] as usize] += 1; - } - matrix[pre[1] as usize][pre[0] as usize] = true; - } - let mut deq = VecDeque::new(); - // BFS starts with nodes with 0 in degree - for (node, &v) in in_degree.iter().enumerate() { - if v == 0 { - deq.push_back(node); - } - } - let mut res = Vec::with_capacity(num); - while let Some(node) = deq.pop_front() { - res.push(node as i32); - for (i, &connect) in matrix[node].iter().enumerate() { - if connect { - in_degree[i] -= 1; - if in_degree[i] == 0 { - deq.push_back(i); - } - } - } - } - if res.len() == num { - res - } else { - vec![] - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_210() { - assert_eq!(Solution::find_order(2, vec![vec![1, 0]]), vec![0, 1]); - assert_eq!( - Solution::find_order(4, vec![vec![1, 0], vec![2, 0], vec![3, 1], vec![3, 2]]), - vec![0, 1, 2, 3] - ); - } -} diff --git a/src/solution/s0211_add_and_search_word_data_structure_design.rs b/src/solution/s0211_add_and_search_word_data_structure_design.rs deleted file mode 100644 index 0652f951..00000000 --- a/src/solution/s0211_add_and_search_word_data_structure_design.rs +++ /dev/null @@ -1,129 +0,0 @@ -/** - * [211] Add and Search Word - Data structure design - * - * Design a data structure that supports the following two operations: - * - * - * void addWord(word) - * bool search(word) - * - * - * search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. - * - * Example: - * - * - * addWord("bad") - * addWord("dad") - * addWord("mad") - * search("pad") -> false - * search("bad") -> true - * search(".ad") -> true - * search("b..") -> true - * - * - * Note:
- * You may assume that all words are consist of lowercase letters a-z. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/add-and-search-word-data-structure-design/ -// discuss: https://leetcode.com/problems/add-and-search-word-data-structure-design/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -struct WordDictionary { - root: Option>, -} - -#[derive(Default)] -struct Trie { - is_end: bool, - marked: Vec, - nodes: [Option>; 26], -} - -impl Trie { - fn new() -> Self { - Default::default() - } -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl WordDictionary { - // /** Initialize your data structure here. */ - // fn new() -> Self { - // WordDictionary{ - // root: Some(Box::new(Trie::new())), - // } - // } - - // /** Adds a word into the data structure. */ - // fn add_word(&mut self, word: String) { - // let mut curr = self.root; - - // for i in word.chars().map(|ch| (ch as u8 - 'a' as u8) as usize) { - // curr = curr.as_ref().unwrap().nodes[i]; - // } - // curr.as_mut().unwrap().is_end = true; - // } - - // /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ - // fn search(&self, word: String) -> bool { - // let mut chs: Vec = word.chars().collect(); - // WordDictionary::search_from(self.root.as_ref(), &mut chs) - // } - - // fn search_from(node: Option<&Box>, chs: &mut [char]) -> bool { - // if node.is_none() { - // return false - // } - // let node = node.unwrap(); - // if chs.len() < 1 { - // return node.is_end - // } - // if chs[0] == '.' { - // // backtracking - // let mut sliced = &mut chs[1..]; - // for &idx in node.marked.iter() { - // if WordDictionary::search_from(node.nodes[idx].as_ref(), sliced) { - // return true - // } - // } - // false - // } else { - // let next = node.nodes[(chs[0] as u8 - 'a' as u8) as usize].as_ref(); - // WordDictionary::search_from(next, &mut chs[1..]) - // } - // } -} - -/** - * Your WordDictionary object will be instantiated and called as such: - * let obj = WordDictionary::new(); - * obj.add_word(word); - * let ret_2: bool = obj.search(word); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_211() { - // let mut dict = WordDictionary::new(); - // dict.add_word("bad".to_owned()); - // dict.add_word("dad".to_owned()); - // dict.add_word("mad".to_owned()); - // assert_eq!(dict.search("pad".to_owned()), false); - // assert_eq!(dict.search("bad".to_owned()), true); - // assert_eq!(dict.search(".ad".to_owned()), true); - // assert_eq!(dict.search("da.".to_owned()), true); - } -} diff --git a/src/solution/s0212_word_search_ii.rs b/src/solution/s0212_word_search_ii.rs deleted file mode 100644 index ada034c8..00000000 --- a/src/solution/s0212_word_search_ii.rs +++ /dev/null @@ -1,57 +0,0 @@ -/** - * [212] Word Search II - * - * Given a 2D board and a list of words from the dictionary, find all words in the board. - * - * 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. - * - * - * - * Example: - * - * - * Input: - * board = [ - * ['o','a','a','n'], - * ['e','t','a','e'], - * ['i','h','k','r'], - * ['i','f','l','v'] - * ] - * words = ["oath","pea","eat","rain"] - * - * Output: ["eat","oath"] - * - * - * - * - * Note: - * - *
    - * All inputs are consist of lowercase letters a-z. - * The values of words are distinct. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/word-search-ii/ -// discuss: https://leetcode.com/problems/word-search-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -// TODO - -impl Solution { - pub fn find_words(board: Vec>, words: Vec) -> Vec { - vec![] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_212() {} -} diff --git a/src/solution/s0213_house_robber_ii.rs b/src/solution/s0213_house_robber_ii.rs deleted file mode 100644 index fbe55040..00000000 --- a/src/solution/s0213_house_robber_ii.rs +++ /dev/null @@ -1,69 +0,0 @@ -/** - * [213] House Robber II - * - * You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. - * - * 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. - * - * Example 1: - * - * - * Input: [2,3,2] - * Output: 3 - * Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), - * because they are adjacent houses. - * - * - * Example 2: - * - * - * Input: [1,2,3,1] - * Output: 4 - * Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). - * Total amount you can rob = 1 + 3 = 4. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/house-robber-ii/ -// discuss: https://leetcode.com/problems/house-robber-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// DP twice: rob first one || not rob first one -// F[i] = max(F[i-2] + num[i], F[i-1]) -impl Solution { - pub fn rob(nums: Vec) -> i32 { - let mut max = i32::min_value(); - for &rob_first in vec![true, false].iter() { - let (mut prev, mut curr) = (0, 0); - for (k, &num) in nums.iter().enumerate() { - if k == 0 && !rob_first { - continue; - } - // k is last element but not the first element - if k != 0 && k == (nums.len() - 1) && rob_first { - continue; - } - let next = i32::max(prev + num, curr); - prev = curr; - curr = next; - } - max = i32::max(max, curr) - } - max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_213() { - assert_eq!(Solution::rob(vec![2, 3, 2]), 3); - assert_eq!(Solution::rob(vec![1, 2, 3, 1]), 4); - } -} diff --git a/src/solution/s0214_shortest_palindrome.rs b/src/solution/s0214_shortest_palindrome.rs deleted file mode 100644 index 425eec95..00000000 --- a/src/solution/s0214_shortest_palindrome.rs +++ /dev/null @@ -1,40 +0,0 @@ -/** - * [214] Shortest Palindrome - * - * 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. - * - * Example 1: - * - * - * Input: "aacecaaa" - * Output: "aaacecaaa" - * - * - * Example 2: - * - * - * Input: "abcd" - * Output: "dcbabcd" - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/shortest-palindrome/ -// discuss: https://leetcode.com/problems/shortest-palindrome/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn shortest_palindrome(s: String) -> String { - "".to_owned() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_214() {} -} diff --git a/src/solution/s0215_kth_largest_element_in_an_array.rs b/src/solution/s0215_kth_largest_element_in_an_array.rs deleted file mode 100644 index 159e7af6..00000000 --- a/src/solution/s0215_kth_largest_element_in_an_array.rs +++ /dev/null @@ -1,62 +0,0 @@ -/** - * [215] Kth Largest Element in an Array - * - * 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. - * - * Example 1: - * - * - * Input: [3,2,1,5,6,4] and k = 2 - * Output: 5 - * - * - * Example 2: - * - * - * Input: [3,2,3,1,2,4,5,5,6] and k = 4 - * Output: 4 - * - * Note:
- * You may assume k is always valid, 1 ≤ k ≤ array's length. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/kth-largest-element-in-an-array/ -// discuss: https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cmp::Reverse; -use std::collections::BinaryHeap; -impl Solution { - pub fn find_kth_largest(nums: Vec, k: i32) -> i32 { - let k = k as usize; - let mut heap = BinaryHeap::with_capacity(k); - for &num in nums.iter() { - if heap.len() < k as usize { - heap.push(Reverse(num)) - } else if num >= heap.peek().unwrap().0 { - heap.pop(); - heap.push(Reverse(num)); - } - } - heap.peek().unwrap().0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_215() { - assert_eq!( - Solution::find_kth_largest(vec![3, 2, 3, 1, 2, 4, 5, 5, 6], 4), - 4 - ); - assert_eq!(Solution::find_kth_largest(vec![3, 2, 1, 5, 6, 4], 2), 5); - } -} diff --git a/src/solution/s0216_combination_sum_iii.rs b/src/solution/s0216_combination_sum_iii.rs deleted file mode 100644 index 0f714e01..00000000 --- a/src/solution/s0216_combination_sum_iii.rs +++ /dev/null @@ -1,83 +0,0 @@ -/** - * [216] Combination Sum III - * - *
- * 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. - * - * Note: - * - * - * All numbers will be positive integers. - * The solution set must not contain duplicate combinations. - * - * - * Example 1: - * - * - * Input: k = 3, n = 7 - * Output: [[1,2,4]] - * - * - * Example 2: - * - * - * Input: k = 3, n = 9 - * Output: [[1,2,6], [1,3,5], [2,3,4]] - * - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/combination-sum-iii/ -// discuss: https://leetcode.com/problems/combination-sum-iii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn combination_sum3(k: i32, n: i32) -> Vec> { - if k > 9 || k < 1 { - return vec![]; - } - let max = (0..k).fold(0, |acc, t| acc + 9 - t); - let min = (0..k).fold(0, |acc, t| acc + t); - if n < min || n > max { - return vec![]; - } - let mut res = Vec::new(); - let mut seed = Vec::new(); - Solution::helper(n, 0, k, seed, &mut res); - res - } - - fn helper(distance: i32, prev: i32, remain: i32, mut curr: Vec, res: &mut Vec>) { - if remain == 0 { - if distance == 0 { - res.push(curr); - } - return; - } - for i in (prev + 1..=9) { - if distance - i < 0 { - break; - } - let mut new_vec = curr.clone(); - new_vec.push(i); - Solution::helper(distance - i, i, remain - 1, new_vec, res); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_216() { - assert_eq!( - Solution::combination_sum3(3, 9), - vec![vec![1, 2, 6], vec![1, 3, 5], vec![2, 3, 4]] - ); - } -} diff --git a/src/solution/s0217_contains_duplicate.rs b/src/solution/s0217_contains_duplicate.rs deleted file mode 100644 index 0d2e5e12..00000000 --- a/src/solution/s0217_contains_duplicate.rs +++ /dev/null @@ -1,65 +0,0 @@ -/** - * [217] Contains Duplicate - * - * Given an array of integers, find if the array contains any duplicates. - * - * 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. - * - * Example 1: - * - * - * Input: [1,2,3,1] - * Output: true - * - * Example 2: - * - * - * Input: [1,2,3,4] - * Output: false - * - * Example 3: - * - * - * Input: [1,1,1,3,3,4,3,2,4,2] - * Output: true - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/contains-duplicate/ -// discuss: https://leetcode.com/problems/contains-duplicate/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn contains_duplicate(nums: Vec) -> bool { - if nums.is_empty() { - return false; - } - let mut nums = nums; - nums.sort_unstable(); - let mut prev = nums[0]; - for i in 1..nums.len() { - if nums[i] == prev { - return true; - } - prev = nums[i] - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_217() { - assert_eq!(Solution::contains_duplicate(vec![1]), false); - assert_eq!(Solution::contains_duplicate(vec![]), false); - assert_eq!(Solution::contains_duplicate(vec![1, 2, 3, 4]), false); - assert_eq!(Solution::contains_duplicate(vec![1, 2, 3, 1]), true); - } -} diff --git a/src/solution/s0218_the_skyline_problem.rs b/src/solution/s0218_the_skyline_problem.rs deleted file mode 100644 index 7f0ba3c1..00000000 --- a/src/solution/s0218_the_skyline_problem.rs +++ /dev/null @@ -1,46 +0,0 @@ -/** - * [218] The Skyline Problem - * - * A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B). - * Buildings Skyline Contour - * - * The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0. - * - * For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] . - * - * The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour. - * - * For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ]. - * - * Notes: - * - * - * The number of buildings in any input list is guaranteed to be in the range [0, 10000]. - * The input list is already sorted in ascending order by the left x position Li. - * The output list must be sorted by the x position. - * There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/the-skyline-problem/ -// discuss: https://leetcode.com/problems/the-skyline-problem/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn get_skyline(buildings: Vec>) -> Vec> { - vec![] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_218() {} -} diff --git a/src/solution/s0219_contains_duplicate_ii.rs b/src/solution/s0219_contains_duplicate_ii.rs deleted file mode 100644 index da446dae..00000000 --- a/src/solution/s0219_contains_duplicate_ii.rs +++ /dev/null @@ -1,79 +0,0 @@ -/** - * [219] Contains Duplicate II - * - * 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. - * - *
- * Example 1: - * - * - * Input: nums = [1,2,3,1], k = 3 - * Output: true - * - * - *
- * Example 2: - * - * - * Input: nums = [1,0,1,1], k = 1 - * Output: true - * - * - *
- * Example 3: - * - * - * Input: nums = [1,2,3,1,2,3], k = 2 - * Output: false - * - *
- *
- *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/contains-duplicate-ii/ -// discuss: https://leetcode.com/problems/contains-duplicate-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::HashMap; -impl Solution { - pub fn contains_nearby_duplicate(nums: Vec, k: i32) -> bool { - let mut map = HashMap::new(); - for (idx, &num) in nums.iter().enumerate() { - match map.get(&num) { - Some(v) => { - if idx - v <= k as usize { - return true; - } - map.insert(num, idx); - } - None => { - map.insert(num, idx); - } - } - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_219() { - assert_eq!( - Solution::contains_nearby_duplicate(vec![1, 2, 3, 1, 2, 3], 2), - false - ); - assert_eq!( - Solution::contains_nearby_duplicate(vec![1, 2, 3, 1, 2, 3], 3), - true - ); - } -} diff --git a/src/solution/s0220_contains_duplicate_iii.rs b/src/solution/s0220_contains_duplicate_iii.rs deleted file mode 100644 index 0677b1d3..00000000 --- a/src/solution/s0220_contains_duplicate_iii.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [220] Contains Duplicate III - * - * Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k. - * - *
- * Example 1: - * - * - * Input: nums = [1,2,3,1], k = 3, t = 0 - * Output: true - * - * - *
- * Example 2: - * - * - * Input: nums = [1,0,1,1], k = 1, t = 2 - * Output: true - * - * - *
- * Example 3: - * - * - * Input: nums = [1,5,9,1,5,9], k = 2, t = 3 - * Output: false - * - *
- *
- *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/contains-duplicate-iii/ -// discuss: https://leetcode.com/problems/contains-duplicate-iii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -use std::collections::HashMap; -impl Solution { - pub fn contains_nearby_almost_duplicate(nums: Vec, k: i32, t: i32) -> bool { - if k < 1 || t < 0 { - return false; - } - let mut map = HashMap::new(); - for i in 0..nums.len() { - let remap = nums[i] as i64 - i32::min_value() as i64; - let bucket = remap / (t as i64 + 1); - println!("{} {}", remap, bucket); - if map.contains_key(&bucket) - || map - .get(&(bucket - 1)) - .map_or(false, |v| remap - v <= t as i64) - || map - .get(&(bucket + 1)) - .map_or(false, |v| v - remap <= t as i64) - { - return true; - } - if i >= k as usize { - let last_bucket = - (nums[i - k as usize] as i64 - i32::min_value() as i64) / (t as i64 + 1); - map.remove(&last_bucket); - } - map.insert(bucket, remap); - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_220() { - // assert_eq!(Solution::contains_nearby_almost_duplicate(vec![1,5,9,1,5,9], 2, 3), false); - // assert_eq!(Solution::contains_nearby_almost_duplicate(vec![1,2,3,1], 3, 0), true); - assert_eq!( - Solution::contains_nearby_almost_duplicate(vec![-1, 2147483647], 1, 2147483647), - false - ); - } -} diff --git a/src/solution/s0221_maximal_square.rs b/src/solution/s0221_maximal_square.rs deleted file mode 100644 index 34f793ac..00000000 --- a/src/solution/s0221_maximal_square.rs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * [221] Maximal Square - * - * Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. - * - * Example: - * - * - * Input: - * - * 1 0 1 0 0 - * 1 0 1 1 1 - * 1 1 1 1 1 - * 1 0 0 1 0 - * - * Output: 4 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/maximal-square/ -// discuss: https://leetcode.com/problems/maximal-square/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -DP, f(i, j) to represent the max square of matrix that end with (i, j) (right bottom corener), then: - -f(0, 0) = matrix[0][0] -f(i, j) = if matrix[0][0] { min(f(i-1,j), f(i,j-1), f(i-1)(j-1)) + 1 } else { 0 } - -The equation explained: - -matrix: dp: -1 1 1 1 1 1 -1 1 1 -> 1 2 2 -1 1 1 1 2 3 -*/ -impl Solution { - pub fn maximal_square(matrix: Vec>) -> i32 { - if matrix.is_empty() || matrix[0].is_empty() { - return 0; - } - let (height, width) = (matrix.len(), matrix[0].len()); - let mut dp = vec![vec![0; width]; height]; - let mut max = 0; - for i in 0..height { - for j in 0..width { - if matrix[i][j] == '0' { - continue; - } - dp[i][j] = i32::min( - i32::min( - if i < 1 { 0 } else { dp[i - 1][j] }, - if j < 1 { 0 } else { dp[i][j - 1] }, - ), - if i < 1 || j < 1 { 0 } else { dp[i - 1][j - 1] }, - ) + 1; - max = i32::max(max, dp[i][j]) - } - } - max * max - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_221() { - assert_eq!( - Solution::maximal_square(vec![ - vec!['1', '0', '1', '0', '0'], - vec!['1', '0', '1', '1', '1'], - vec!['1', '1', '1', '1', '1'], - vec!['1', '0', '0', '1', '0'], - ]), - 4 - ) - } -} diff --git a/src/solution/s0222_count_complete_tree_nodes.rs b/src/solution/s0222_count_complete_tree_nodes.rs deleted file mode 100644 index ae0d410b..00000000 --- a/src/solution/s0222_count_complete_tree_nodes.rs +++ /dev/null @@ -1,88 +0,0 @@ -/** - * [222] Count Complete Tree Nodes - * - * Given a complete binary tree, count the number of nodes. - * - * Note: - * - * Definition of a complete binary tree from Wikipedia:
- * In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2^h nodes inclusive at the last level h. - * - * Example: - * - * - * Input: - * 1 - * / \ - * 2 3 - * / \ / - * 4 5 6 - * - * Output: 6 - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/count-complete-tree-nodes/ -// discuss: https://leetcode.com/problems/count-complete-tree-nodes/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn count_nodes(root: Option>>) -> i32 { - // 0. get the hight of full nodes - let mut height = 0; - let mut curr = root.clone(); - let mut result = 0; - while let Some(inner) = curr { - height += 1; - result += 2_i32.pow(height - 1); - curr = inner.borrow().right.clone(); - } - if height == 0 { - return result; - } - // 1. 'binary search' to find the node number of the lowest level - // the lowest level may have 0~2^H-1 node - let mut curr_root = root.clone(); - while height > 1 { - // see if left tree is full - let mut node = curr_root.clone().unwrap().borrow().left.clone(); - let mut level = 2; - while level < height { - node = node.unwrap().borrow().right.clone(); - level += 1; - } - if node.unwrap().borrow().right.is_some() { - curr_root = curr_root.unwrap().borrow().right.clone(); - result += 2_i32.pow(height - 1); - } else { - curr_root = curr_root.unwrap().borrow().left.clone(); - } - height -= 1; - } - if curr_root.as_ref().unwrap().borrow().left.is_some() { - result += 1; - } - result - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_222() { - assert_eq!(Solution::count_nodes(tree![1, 1, 1, 1, 1, 1, 1]), 7); - assert_eq!(Solution::count_nodes(tree![]), 0); - assert_eq!(Solution::count_nodes(tree![1, 1]), 2); - assert_eq!(Solution::count_nodes(tree![1]), 1); - assert_eq!(Solution::count_nodes(tree![1, 1, 1]), 3); - } -} diff --git a/src/solution/s0223_rectangle_area.rs b/src/solution/s0223_rectangle_area.rs deleted file mode 100644 index 647b6b2a..00000000 --- a/src/solution/s0223_rectangle_area.rs +++ /dev/null @@ -1,62 +0,0 @@ -/** - * [223] Rectangle Area - * - * Find the total area covered by two rectilinear rectangles in a 2D plane. - * - * Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. - * - * Rectangle Area - * - * Example: - * - * - * Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2 - * Output: 45 - * - * Note: - * - * Assume that the total area is never beyond the maximum possible value of int. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/rectangle-area/ -// discuss: https://leetcode.com/problems/rectangle-area/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// mention the integer divition -impl Solution { - pub fn compute_area(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32, h: i32) -> i32 { - let center1 = ((a + c), (b + d)); - let center2 = ((e + g), (f + h)); - let rect1 = (c - a, d - b); - let rect2 = (g - e, h - f); - let x_intersect = i32::min( - (rect1.0 + rect2.0 - (center1.0 - center2.0).abs()), - i32::min(2 * rect1.0, 2 * rect2.0), - ) / 2; - let x_intersect = if x_intersect < 0 { 0 } else { x_intersect }; - let y_intersect = i32::min( - (rect1.1 + rect2.1 - (center1.1 - center2.1).abs()), - i32::min(2 * rect1.1, 2 * rect2.1), - ) / 2; - let y_intersect = if y_intersect < 0 { 0 } else { y_intersect }; - rect1.0 * rect1.1 - x_intersect * y_intersect + rect2.0 * rect2.1 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_223() { - assert_eq!(Solution::compute_area(0, 0, 0, 0, 0, 0, 0, 0), 0); - assert_eq!(Solution::compute_area(-3, 0, 3, 4, 0, -1, 9, 2), 45); - assert_eq!(Solution::compute_area(-2, -2, 2, 2, -2, -2, 2, 2), 16); - assert_eq!(Solution::compute_area(-2, -2, 2, 2, -1, 4, 1, 6), 20); - } -} diff --git a/src/solution/s0224_basic_calculator.rs b/src/solution/s0224_basic_calculator.rs deleted file mode 100644 index 5d917661..00000000 --- a/src/solution/s0224_basic_calculator.rs +++ /dev/null @@ -1,156 +0,0 @@ -/** - * [224] Basic Calculator - * - * Implement a basic calculator to evaluate a simple expression string. - * - * The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . - * - * Example 1: - * - * - * Input: "1 + 1" - * Output: 2 - * - * - * Example 2: - * - * - * Input: " 2-1 + 2 " - * Output: 3 - * - * Example 3: - * - * - * Input: "(1+(4+5+2)-3)+(6+8)" - * Output: 23 - * Note: - * - * - * You may assume that the given expression is always valid. - * Do not use the eval built-in library function. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/basic-calculator/ -// discuss: https://leetcode.com/problems/basic-calculator/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -#[derive(PartialEq, Copy, Clone, Debug)] -enum Token { - LeftBracket, - RightBracket, - PlusSign, - MinusSign, - Number(i64), -} - -impl Solution { - pub fn calculate(s: String) -> i32 { - // lexer - let mut token_stream = Vec::new(); - let mut num = 0_i64; - let mut in_num = false; - for ch in s.chars() { - match ch { - '0'..='9' => { - in_num = true; - num = 10 * num + (ch as u8 - '0' as u8) as i64; - } - _ => { - if in_num { - token_stream.push(Token::Number(num)); - num = 0; - in_num = false; - } - match ch { - '(' => { - token_stream.push(Token::LeftBracket); - } - ')' => { - token_stream.push(Token::RightBracket); - } - '+' => { - token_stream.push(Token::PlusSign); - } - '-' => { - token_stream.push(Token::MinusSign); - } - _ => {} - }; - } - } - } - if in_num { - token_stream.push(Token::Number(num)); - } - - // parser - let mut stack = Vec::new(); - let mut iter = token_stream.into_iter(); - let mut pause = false; - let mut token = Token::LeftBracket; - loop { - if !pause { - token = if let Some(token) = iter.next() { - token - } else { - break; - } - } else { - pause = false; - } - match token { - Token::LeftBracket => { - stack.push(token); - } - Token::RightBracket => { - if let Token::Number(right_hand) = stack.pop().unwrap() { - stack.pop(); - pause = true; - token = Token::Number(right_hand); - } - } - Token::PlusSign => { - stack.push(token); - } - Token::MinusSign => { - stack.push(token); - } - Token::Number(num) => { - if stack.is_empty() || Token::LeftBracket == *stack.last().unwrap() { - stack.push(Token::Number(num)); - } else { - let sign = stack.pop().unwrap(); - if let Token::Number(left_hand) = stack.pop().unwrap() { - let res = - left_hand + num * if Token::PlusSign == sign { 1 } else { -1 }; - stack.push(Token::Number(res)); - } - } - } - } - } - if let Token::Number(num) = stack.pop().unwrap() { - return num as i32; - } - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_224() { - assert_eq!(Solution::calculate("(1+(4+5+2)-3)+(6+8)".to_owned()), 23); - assert_eq!(Solution::calculate("1+1".to_owned()), 2); - assert_eq!(Solution::calculate("0".to_owned()), 0); - assert_eq!(Solution::calculate("2147483647".to_owned()), 2147483647); - } -} diff --git a/src/solution/s0225_implement_stack_using_queues.rs b/src/solution/s0225_implement_stack_using_queues.rs deleted file mode 100644 index f162e9a6..00000000 --- a/src/solution/s0225_implement_stack_using_queues.rs +++ /dev/null @@ -1,125 +0,0 @@ -/** - * [225] Implement Stack using Queues - * - * Implement the following operations of a stack using queues. - * - * - * push(x) -- Push element x onto stack. - * pop() -- Removes the element on top of the stack. - * top() -- Get the top element. - * empty() -- Return whether the stack is empty. - * - * - * Example: - * - * - * MyStack stack = new MyStack(); - * - * stack.push(1); - * stack.push(2); - * stack.top(); // returns 2 - * stack.pop(); // returns 2 - * stack.empty(); // returns false - * - * Notes: - * - * - * You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid. - * Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue. - * You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack). - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/implement-stack-using-queues/ -// discuss: https://leetcode.com/problems/implement-stack-using-queues/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -struct MyStack { - q1: VecDeque, - q2: VecDeque, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -use std::collections::VecDeque; -impl MyStack { - /** Initialize your data structure here. */ - fn new() -> Self { - MyStack { - q1: VecDeque::new(), - q2: VecDeque::new(), - } - } - - /** Push element x onto stack. */ - fn push(&mut self, x: i32) { - if self.q1.is_empty() { - self.q1.push_back(x); - while let Some(v) = self.q2.pop_front() { - self.q1.push_back(v); - } - } else { - self.q2.push_back(x); - while let Some(v) = self.q1.pop_front() { - self.q2.push_back(v); - } - } - } - - /** Removes the element on top of the stack and returns that element. */ - fn pop(&mut self) -> i32 { - if self.q1.is_empty() { - self.q2.pop_front().unwrap() - } else { - self.q1.pop_front().unwrap() - } - } - - /** Get the top element. */ - fn top(&self) -> i32 { - if self.q1.is_empty() { - *self.q2.front().unwrap() - } else { - *self.q1.front().unwrap() - } - } - - /** Returns whether the stack is empty. */ - fn empty(&self) -> bool { - self.q1.is_empty() && self.q2.is_empty() - } -} - -/** - * Your MyStack object will be instantiated and called as such: - * let obj = MyStack::new(); - * obj.push(x); - * let ret_2: i32 = obj.pop(); - * let ret_3: i32 = obj.top(); - * let ret_4: bool = obj.empty(); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_225() { - let mut stack = MyStack::new(); - - stack.push(1); - stack.push(2); - assert_eq!(stack.top(), 2); // returns 2 - assert_eq!(stack.pop(), 2); // returns 2 - assert_eq!(stack.empty(), false); // returns false - assert_eq!(stack.pop(), 1); - assert_eq!(stack.empty(), true); - } -} diff --git a/src/solution/s0226_invert_binary_tree.rs b/src/solution/s0226_invert_binary_tree.rs deleted file mode 100644 index 1a1b6115..00000000 --- a/src/solution/s0226_invert_binary_tree.rs +++ /dev/null @@ -1,69 +0,0 @@ -/** - * [226] Invert Binary Tree - * - * Invert a binary tree. - * - * Example: - * - * Input: - * - * - * 4 - * / \ - * 2 7 - * / \ / \ - * 1 3 6 9 - * - * Output: - * - * - * 4 - * / \ - * 7 2 - * / \ / \ - * 9 6 3 1 - * - * Trivia:
- * This problem was inspired by this original tweet by Max Howell: - * - *
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.
- * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/invert-binary-tree/ -// discuss: https://leetcode.com/problems/invert-binary-tree/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn invert_tree(root: Option>>) -> Option>> { - if let Some(node) = root.clone() { - Solution::invert_tree(node.borrow().right.clone()); - Solution::invert_tree(node.borrow().left.clone()); - let left = node.borrow().left.clone(); - let right = node.borrow().right.clone(); - node.borrow_mut().left = right; - node.borrow_mut().right = left; - } - root - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_226() { - assert_eq!( - Solution::invert_tree(tree![4, 2, 7, 1, 3, 6, 9]), - tree![4, 7, 2, 9, 6, 3, 1] - ); - } -} diff --git a/src/solution/s0227_basic_calculator_ii.rs b/src/solution/s0227_basic_calculator_ii.rs deleted file mode 100644 index 07e349dd..00000000 --- a/src/solution/s0227_basic_calculator_ii.rs +++ /dev/null @@ -1,107 +0,0 @@ -/** - * [227] Basic Calculator II - * - * Implement a basic calculator to evaluate a simple expression string. - * - * The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. - * - * Example 1: - * - * - * Input: "3+2*2" - * Output: 7 - * - * - * Example 2: - * - * - * Input: " 3/2 " - * Output: 1 - * - * Example 3: - * - * - * Input: " 3+5 / 2 " - * Output: 5 - * - * - * Note: - * - * - * You may assume that the given expression is always valid. - * Do not use the eval built-in library function. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/basic-calculator-ii/ -// discuss: https://leetcode.com/problems/basic-calculator-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn calculate(s: String) -> i32 { - let mut acc = 0_i64; - let mut prev = 0_i64; - let mut curr = 0_i64; - let mut sign = 1; - let mut has_prev = false; - let mut multiple = true; - for ch in s.chars() { - match ch { - '0'..='9' => { - curr = 10 * curr + (ch as u8 - '0' as u8) as i64; - } - '+' | '-' => { - if has_prev { - if multiple { - curr = prev * curr; - } else { - curr = prev / curr; - } - has_prev = false; - } - acc += curr * sign; - curr = 0; - sign = if ch == '+' { 1 } else { -1 }; - } - '*' | '/' => { - if has_prev { - if multiple { - curr = prev * curr; - } else { - curr = prev / curr; - } - } - has_prev = true; - prev = curr; - curr = 0; - multiple = if ch == '*' { true } else { false }; - } - _ => {} - } - } - if has_prev { - if multiple { - curr = prev * curr; - } else { - curr = prev / curr; - } - } - acc += sign * curr; - acc as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_227() { - assert_eq!(Solution::calculate("3+2*2".to_owned()), 7); - } -} diff --git a/src/solution/s0228_summary_ranges.rs b/src/solution/s0228_summary_ranges.rs deleted file mode 100644 index 63e8fe77..00000000 --- a/src/solution/s0228_summary_ranges.rs +++ /dev/null @@ -1,74 +0,0 @@ -/** - * [228] Summary Ranges - * - * Given a sorted integer array without duplicates, return the summary of its ranges. - * - * Example 1: - * - * - * Input: [0,1,2,4,5,7] - * Output: ["0->2","4->5","7"] - * Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range. - * - * - * Example 2: - * - * - * Input: [0,2,3,4,6,8,9] - * Output: ["0","2->4","6","8->9"] - * Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/summary-ranges/ -// discuss: https://leetcode.com/problems/summary-ranges/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn summary_ranges(nums: Vec) -> Vec { - if nums.is_empty() { - return vec![]; - } - let mut res = Vec::new(); - let mut curr = nums[0]; - let mut start = nums[0]; - for num in nums.into_iter().skip(1) { - if num == curr + 1 { - curr = num; - } else { - // seq done - Solution::record(&mut res, start, curr); - start = num; - curr = num; - } - } - Solution::record(&mut res, start, curr); - res - } - - pub fn record(vec: &mut Vec, start: i32, end: i32) { - if start == end { - vec.push(format!("{}", start)) - } else { - vec.push(format!("{}->{}", start, end)) - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_228() { - assert_eq!( - Solution::summary_ranges(vec![0, 1, 2, 3, 4, 5, 6]), - vec_string!["0->6"] - ); - } -} diff --git a/src/solution/s0229_majority_element_ii.rs b/src/solution/s0229_majority_element_ii.rs deleted file mode 100644 index fab987ba..00000000 --- a/src/solution/s0229_majority_element_ii.rs +++ /dev/null @@ -1,87 +0,0 @@ -/** - * [229] Majority Element II - * - * Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. - * - * Note: The algorithm should run in linear time and in O(1) space. - * - * Example 1: - * - * - * Input: [3,2,3] - * Output: [3] - * - * Example 2: - * - * - * Input: [1,1,1,3,3,2,2,2] - * Output: [1,2] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/majority-element-ii/ -// discuss: https://leetcode.com/problems/majority-element-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn majority_element(nums: Vec) -> Vec { - if nums.is_empty() { - return vec![]; - } - let (mut vote0, mut vote1, mut candidate0, mut candidate1) = (0, 0, -1, -2); - for &num in nums.iter() { - if num == candidate0 { - vote0 += 1; - } else if num == candidate1 { - vote1 += 1; - } else if vote0 == 0 { - candidate0 = num; - vote0 = 1; - } else if vote1 == 0 { - candidate1 = num; - vote1 = 1; - } else { - vote0 -= 1; - vote1 -= 1; - } - } - // the presents of majority element is not guaranteed, we have to do a double check - let mut res = Vec::new(); - for &v in vec![candidate0, candidate1].iter() { - let mut count = 0; - for &num in nums.iter() { - if v == num { - count += 1; - } - } - if count > (nums.len() / 3) as i32 { - res.push(v); - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_229() { - assert_eq!( - Solution::majority_element(vec![1, 1, 1, 2, 2, 2, 3, 3, 3]), - vec![] - ); - assert_eq!( - Solution::majority_element(vec![1, 1, 1, 2, 2, 3, 3, 3]), - vec![1, 3] - ); - assert_eq!(Solution::majority_element(vec![1]), vec![1]); - assert_eq!(Solution::majority_element(vec![5, 6, 6]), vec![6]); - assert_eq!(Solution::majority_element(vec![1, 2, 3, 4]), vec![]); - } -} diff --git a/src/solution/s0230_kth_smallest_element_in_a_bst.rs b/src/solution/s0230_kth_smallest_element_in_a_bst.rs deleted file mode 100644 index 0533f705..00000000 --- a/src/solution/s0230_kth_smallest_element_in_a_bst.rs +++ /dev/null @@ -1,84 +0,0 @@ -/** - * [230] Kth Smallest Element in a BST - * - * Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. - * - * Note:
- * You may assume k is always valid, 1 ≤ k ≤ BST's total elements. - * - * Example 1: - * - * - * Input: root = [3,1,4,null,2], k = 1 - * 3 - * / \ - * 1 4 - * \ - * 2 - * Output: 1 - * - * Example 2: - * - * - * Input: root = [5,3,6,2,4,null,null,1], k = 3 - * 5 - * / \ - * 3 6 - * / \ - * 2 4 - * / - * 1 - * Output: 3 - * - * - * Follow up:
- * What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/kth-smallest-element-in-a-bst/ -// discuss: https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn kth_smallest(root: Option>>, k: i32) -> i32 { - let mut res = 0; - Solution::helper(root, k, &mut res); - res - } - - pub fn helper(root: Option>>, k: i32, res: &mut i32) -> i32 { - if k <= 0 { - return 0; - } - if let Some(node) = root { - let left = Solution::helper(node.borrow().left.clone(), k, res); - if left == 1 { - *res = node.borrow().val; - } - let right = Solution::helper(node.borrow().right.clone(), left - 1, res); - right - } else { - k - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_230() { - assert_eq!(Solution::kth_smallest(tree![3, 1, 4, null, 2], 1), 1); - assert_eq!(Solution::kth_smallest(tree![3, 1, 4, null, 2], 2), 2); - assert_eq!(Solution::kth_smallest(tree![3, 1, 4, null, 2], 3), 3); - } -} diff --git a/src/solution/s0231_power_of_two.rs b/src/solution/s0231_power_of_two.rs deleted file mode 100644 index 334fc314..00000000 --- a/src/solution/s0231_power_of_two.rs +++ /dev/null @@ -1,54 +0,0 @@ -/** - * [231] Power of Two - * - * Given an integer, write a function to determine if it is a power of two. - * - * Example 1: - * - * - * Input: 1 - * Output: true - * Explanation: 2^0 = 1 - * - * - * Example 2: - * - * - * Input: 16 - * Output: true - * Explanation: 2^4 = 16 - * - * Example 3: - * - * - * Input: 218 - * Output: false - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/power-of-two/ -// discuss: https://leetcode.com/problems/power-of-two/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn is_power_of_two(n: i32) -> bool { - let results: Vec = (0..31).map(|x| 2_i32.pow(x)).collect(); - results.binary_search(&n).is_ok() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_231() { - assert_eq!(Solution::is_power_of_two(-1), false); - assert_eq!(Solution::is_power_of_two(1), true); - assert_eq!(Solution::is_power_of_two(1024), true); - } -} diff --git a/src/solution/s0232_implement_queue_using_stacks.rs b/src/solution/s0232_implement_queue_using_stacks.rs deleted file mode 100644 index 70bf3735..00000000 --- a/src/solution/s0232_implement_queue_using_stacks.rs +++ /dev/null @@ -1,110 +0,0 @@ -/** - * [232] Implement Queue using Stacks - * - * Implement the following operations of a queue using stacks. - * - * - * push(x) -- Push element x to the back of queue. - * pop() -- Removes the element from in front of queue. - * peek() -- Get the front element. - * empty() -- Return whether the queue is empty. - * - * - * Example: - * - * - * MyQueue queue = new MyQueue(); - * - * queue.push(1); - * queue.push(2); - * queue.peek(); // returns 1 - * queue.pop(); // returns 1 - * queue.empty(); // returns false - * - * Notes: - * - * - * You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. - * Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. - * You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/implement-queue-using-stacks/ -// discuss: https://leetcode.com/problems/implement-queue-using-stacks/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -struct MyQueue { - vec1: Vec, - vec2: Vec, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl MyQueue { - /** Initialize your data structure here. */ - fn new() -> Self { - MyQueue { - vec1: Vec::new(), - vec2: Vec::new(), - } - } - - /** Push element x to the back of queue. */ - fn push(&mut self, x: i32) { - while let Some(v) = self.vec1.pop() { - self.vec2.push(v); - } - self.vec2.push(x); - while let Some(v) = self.vec2.pop() { - self.vec1.push(v); - } - } - - /** Removes the element from in front of queue and returns that element. */ - fn pop(&mut self) -> i32 { - self.vec1.pop().unwrap() - } - - /** Get the front element. */ - fn peek(&self) -> i32 { - *self.vec1.last().unwrap() - } - - /** Returns whether the queue is empty. */ - fn empty(&self) -> bool { - self.vec1.is_empty() - } -} - -/** - * Your MyQueue object will be instantiated and called as such: - * let obj = MyQueue::new(); - * obj.push(x); - * let ret_2: i32 = obj.pop(); - * let ret_3: i32 = obj.peek(); - * let ret_4: bool = obj.empty(); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_232() { - let mut queue = MyQueue::new(); - - queue.push(1); - queue.push(2); - assert_eq!(queue.peek(), 1); // returns 1 - assert_eq!(queue.pop(), 1); // returns 1 - assert_eq!(queue.empty(), false); // returns false - } -} diff --git a/src/solution/s0233_number_of_digit_one.rs b/src/solution/s0233_number_of_digit_one.rs deleted file mode 100644 index 60097ed0..00000000 --- a/src/solution/s0233_number_of_digit_one.rs +++ /dev/null @@ -1,36 +0,0 @@ -/** - * [233] Number of Digit One - * - * Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. - * - * Example: - * - * - * Input: 13 - * Output: 6 - * Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/number-of-digit-one/ -// discuss: https://leetcode.com/problems/number-of-digit-one/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn count_digit_one(n: i32) -> i32 { - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_233() {} -} diff --git a/src/solution/s0238_product_of_array_except_self.rs b/src/solution/s0238_product_of_array_except_self.rs deleted file mode 100644 index ef5683c4..00000000 --- a/src/solution/s0238_product_of_array_except_self.rs +++ /dev/null @@ -1,65 +0,0 @@ -/** - * [238] Product of Array Except Self - * - * 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]. - * - * Example: - * - * - * Input: [1,2,3,4] - * Output: [24,12,8,6] - * - * - * Note: Please solve it without division and in O(n). - * - * Follow up:
- * Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/product-of-array-except-self/ -// discuss: https://leetcode.com/problems/product-of-array-except-self/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -x 2 3 4 = 24 -1 x 3 4 = 12 -1 2 x 4 = 8 -1 2 3 x = 6 - */ -impl Solution { - pub fn product_except_self(nums: Vec) -> Vec { - if nums.len() < 2 { - return vec![]; - } - let mut res = vec![1; nums.len()]; - let mut n = 1; - for i in (0..nums.len() - 1).rev() { - n *= nums[i + 1]; - res[i] = n; - } - n = 1; - for i in 1..nums.len() { - n *= nums[i - 1]; - res[i] *= n; - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_238() { - assert_eq!( - Solution::product_except_self(vec![1, 2, 3, 4]), - vec![24, 12, 8, 6] - ); - } -} diff --git a/src/solution/s0239_sliding_window_maximum.rs b/src/solution/s0239_sliding_window_maximum.rs deleted file mode 100644 index f7509cb9..00000000 --- a/src/solution/s0239_sliding_window_maximum.rs +++ /dev/null @@ -1,95 +0,0 @@ -/** - * [239] Sliding Window Maximum - * - * Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. - * - * Example: - * - * - * Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3 - * Output: [3,3,5,5,6,7] - * Explanation: - * - * Window position Max - * --------------- ----- - * [1 3 -1] -3 5 3 6 7 3 - * 1 [3 -1 -3] 5 3 6 7 3 - * 1 3 [-1 -3 5] 3 6 7 5 - * 1 3 -1 [-3 5 3] 6 7 5 - * 1 3 -1 -3 [5 3 6] 7 6 - * 1 3 -1 -3 5 [3 6 7] 7 - * - * - * Note:
- * You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array. - * - * Follow up:
- * Could you solve it in linear time? - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/sliding-window-maximum/ -// discuss: https://leetcode.com/problems/sliding-window-maximum/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::VecDeque; -impl Solution { - pub fn max_sliding_window(nums: Vec, k: i32) -> Vec { - let mut deq: VecDeque<(usize, i32)> = VecDeque::new(); - let mut res = Vec::new(); - for i in 0..nums.len() { - // maintain sliding window - if !deq.is_empty() && (*deq.front().unwrap()).0 as i32 <= (i as i32) - k { - deq.pop_front(); - let mut max = i32::min_value(); - let mut count = 0_usize; - for (j, &v) in deq.iter().enumerate() { - if v.1 >= max { - max = v.1; - count = j; - } - } - for _ in 0..count { - deq.pop_front(); - } - } - let num = nums[i]; - if !deq.is_empty() && (*deq.front().unwrap()).1 <= num { - while !deq.is_empty() { - deq.pop_front(); - } - } - deq.push_back((i, num)); - if i + 1 >= k as usize { - res.push((*deq.front().unwrap()).1); - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_239() { - assert_eq!( - Solution::max_sliding_window(vec![9, 10, 9, -7, -4, -8, 2, -6], 5), - vec![10, 10, 9, 2] - ); - assert_eq!( - Solution::max_sliding_window(vec![1, 3, 1, 2, 0, 5], 3), - vec![3, 3, 2, 5] - ); - assert_eq!(Solution::max_sliding_window(vec![7, 2, 4], 2), vec![7, 4]); - assert_eq!(Solution::max_sliding_window(vec![1, -1], 1), vec![1, -1]); - assert_eq!( - Solution::max_sliding_window(vec![1, 3, -1, -3, 5, 3, 6, 7], 3), - vec![3, 3, 5, 5, 6, 7] - ); - } -} diff --git a/src/solution/s0241_different_ways_to_add_parentheses.rs b/src/solution/s0241_different_ways_to_add_parentheses.rs deleted file mode 100644 index a76bfa6a..00000000 --- a/src/solution/s0241_different_ways_to_add_parentheses.rs +++ /dev/null @@ -1,81 +0,0 @@ -/** - * [241] Different Ways to Add Parentheses - * - * Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *. - * - * Example 1: - * - * - * Input: "2-1-1" - * Output: [0, 2] - * Explanation: - * ((2-1)-1) = 0 - * (2-(1-1)) = 2 - * - * Example 2: - * - * - * Input: "2*3-4*5" - * Output: [-34, -14, -10, -10, 10] - * Explanation: - * (2*(3-(4*5))) = -34 - * ((2*3)-(4*5)) = -14 - * ((2*(3-4))*5) = -10 - * (2*((3-4)*5)) = -10 - * (((2*3)-4)*5) = 10 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/different-ways-to-add-parentheses/ -// discuss: https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn diff_ways_to_compute(input: String) -> Vec { - Solution::helper(&input) - } - - pub fn helper(input: &str) -> Vec { - if input.is_empty() { - return vec![]; - } - if let Ok(digit) = input.parse::() { - return vec![digit]; - } - let mut res: Vec = Vec::new(); - for (i, ch) in input.chars().enumerate() { - if ch == '+' || ch == '-' || ch == '*' { - let left = Solution::helper(&input[..i]); - let right = Solution::helper(&input[i + 1..]); - for &a in left.iter() { - for &b in right.iter() { - res.push(match ch { - '+' => a + b, - '-' => a - b, - '*' => a * b, - _ => unreachable!(), - }) - } - } - } - } - res - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_241() { - assert_eq!( - Solution::diff_ways_to_compute("2*3-4*5".to_owned()), - vec![-34, -10, -14, -10, 10] - ); - } -} diff --git a/src/solution/s0242_valid_anagram.rs b/src/solution/s0242_valid_anagram.rs deleted file mode 100644 index ba7a58ae..00000000 --- a/src/solution/s0242_valid_anagram.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [242] Valid Anagram - * - * Given two strings s and t , write a function to determine if t is an anagram of s. - * - * Example 1: - * - * - * Input: s = "anagram", t = "nagaram" - * Output: true - * - * - * Example 2: - * - * - * Input: s = "rat", t = "car" - * Output: false - * - * - * Note:
- * You may assume the string contains only lowercase alphabets. - * - * Follow up:
- * What if the inputs contain unicode characters? How would you adapt your solution to such case? - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/valid-anagram/ -// discuss: https://leetcode.com/problems/valid-anagram/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn is_anagram(s: String, t: String) -> bool { - Solution::hit(s) == Solution::hit(t) - } - - fn hit(s: String) -> Vec { - let mut hit = vec![0; 27]; - for ch in s.chars() { - hit[(ch as u8 - 'a' as u8) as usize] += 1; - } - hit - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_242() { - assert_eq!( - Solution::is_anagram("anagram".to_owned(), "nagaram".to_owned()), - true - ); - } -} diff --git a/src/solution/s0257_binary_tree_paths.rs b/src/solution/s0257_binary_tree_paths.rs deleted file mode 100644 index 6c7833e2..00000000 --- a/src/solution/s0257_binary_tree_paths.rs +++ /dev/null @@ -1,85 +0,0 @@ -/** - * [257] Binary Tree Paths - * - * Given a binary tree, return all root-to-leaf paths. - * - * Note: A leaf is a node with no children. - * - * Example: - * - * - * Input: - * - * 1 - * / \ - * 2 3 - * \ - * 5 - * - * Output: ["1->2->5", "1->3"] - * - * Explanation: All root-to-leaf paths are: 1->2->5, 1->3 - * - */ -pub struct Solution {} -use crate::util::tree::{to_tree, TreeNode}; - -// problem: https://leetcode.com/problems/binary-tree-paths/ -// discuss: https://leetcode.com/problems/binary-tree-paths/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// Definition for a binary tree node. -// #[derive(Debug, PartialEq, Eq)] -// pub struct TreeNode { -// pub val: i32, -// pub left: Option>>, -// pub right: Option>>, -// } -// -// impl TreeNode { -// #[inline] -// pub fn new(val: i32) -> Self { -// TreeNode { -// val, -// left: None, -// right: None -// } -// } -// } -use std::cell::RefCell; -use std::rc::Rc; -impl Solution { - pub fn binary_tree_paths(root: Option>>) -> Vec { - let mut res = Vec::new(); - Solution::helper(root, "".to_owned(), &mut res); - res - } - - fn helper(root: Option>>, path: String, res: &mut Vec) { - if let Some(inner) = root { - if inner.borrow().left.is_none() && inner.borrow().right.is_none() { - res.push(format!("{}{}", path, inner.borrow().val)); - } else { - let path = format!("{}{}->", path, inner.borrow().val); - Solution::helper(inner.borrow().left.clone(), path.clone(), res); - Solution::helper(inner.borrow().right.clone(), path, res); - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_257() { - assert_eq!( - Solution::binary_tree_paths(tree![1, 2, 3, null, 5]), - vec_string!["1->2->5", "1->3"] - ); - } -} diff --git a/src/solution/s0258_add_digits.rs b/src/solution/s0258_add_digits.rs deleted file mode 100644 index 2248be1d..00000000 --- a/src/solution/s0258_add_digits.rs +++ /dev/null @@ -1,41 +0,0 @@ -/** - * [258] Add Digits - * - * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. - * - * Example: - * - * - * Input: 38 - * Output: 2 - * Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. - * Since 2 has only one digit, return it. - * - * - * Follow up:
- * Could you do it without any loop/recursion in O(1) runtime? - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/add-digits/ -// discuss: https://leetcode.com/problems/add-digits/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn add_digits(num: i32) -> i32 { - 1 + ((num - 1) % 9) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_258() { - assert_eq!(Solution::add_digits(1234), 1); - } -} diff --git a/src/solution/s0260_single_number_iii.rs b/src/solution/s0260_single_number_iii.rs deleted file mode 100644 index 09d7a920..00000000 --- a/src/solution/s0260_single_number_iii.rs +++ /dev/null @@ -1,57 +0,0 @@ -/** - * [260] Single Number III - * - * 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. - * - * Example: - * - * - * Input: [1,2,1,3,2,5] - * Output: [3,5] - * - * Note: - * - *
    - * The order of the result is not important. So in the above example, [5, 3] is also correct. - * Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/single-number-iii/ -// discuss: https://leetcode.com/problems/single-number-iii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn single_number(nums: Vec) -> Vec { - let mut res = 0; - for &num in nums.iter() { - res = res ^ num; - } - let right_most_set_bit = res & !(res - 1); - let mut bit_set = 0; - let mut bit_unset = 0; - for &num in nums.iter() { - if num & right_most_set_bit == 0 { - bit_unset = bit_unset ^ num; - } else { - bit_set = bit_set ^ num; - } - } - return vec![bit_set, bit_unset]; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_260() { - assert_eq!(Solution::single_number(vec![1, 2, 1, 2, 3, 4]), vec![3, 4]); - assert_eq!(Solution::single_number(vec![1, 2, 1, 3, 2, 5]), vec![3, 5]); - } -} diff --git a/src/solution/s0263_ugly_number.rs b/src/solution/s0263_ugly_number.rs deleted file mode 100644 index 9ef3bf57..00000000 --- a/src/solution/s0263_ugly_number.rs +++ /dev/null @@ -1,73 +0,0 @@ -/** - * [263] Ugly Number - * - * Write a program to check whether a given number is an ugly number. - * - * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. - * - * Example 1: - * - * - * Input: 6 - * Output: true - * Explanation: 6 = 2 × 3 - * - * Example 2: - * - * - * Input: 8 - * Output: true - * Explanation: 8 = 2 × 2 × 2 - * - * - * Example 3: - * - * - * Input: 14 - * Output: false - * Explanation: 14 is not ugly since it includes another prime factor 7. - * - * - * Note: - * - *
    - * 1 is typically treated as an ugly number. - * Input is within the 32-bit signed integer range: [-2^31, 2^31 - 1]. - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/ugly-number/ -// discuss: https://leetcode.com/problems/ugly-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn is_ugly(num: i32) -> bool { - if num <= 0 { - false - } else if num == 1 { - true - } else if num % 5 == 0 { - Solution::is_ugly(num / 5) - } else if num % 3 == 0 { - Solution::is_ugly(num / 3) - } else if num % 2 == 0 { - Solution::is_ugly(num / 2) - } else { - false - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_263() { - assert_eq!(Solution::is_ugly(25), true); - } -} diff --git a/src/solution/s0264_ugly_number_ii.rs b/src/solution/s0264_ugly_number_ii.rs deleted file mode 100644 index 8dda4f01..00000000 --- a/src/solution/s0264_ugly_number_ii.rs +++ /dev/null @@ -1,66 +0,0 @@ -/** - * [264] Ugly Number II - * - * Write a program to find the n-th ugly number. - * - * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. - * - * Example: - * - * - * Input: n = 10 - * Output: 12 - * Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. - * - * Note: - * - *
    - * 1 is typically treated as an ugly number. - * n does not exceed 1690. - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/ugly-number-ii/ -// discuss: https://leetcode.com/problems/ugly-number-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn nth_ugly_number(n: i32) -> i32 { - let mut base2 = 0; - let mut base3 = 0; - let mut base5 = 0; - let mut ugly = vec![1; 1]; - for _ in 1..n { - let next2 = ugly[base2] * 2; - let next3 = ugly[base3] * 3; - let next5 = ugly[base5] * 5; - let next = i32::min(next2, i32::min(next3, next5)); - if next2 == next { - base2 += 1 - } - if next3 == next { - base3 += 1 - } - if next5 == next { - base5 += 1 - } - ugly.push(next) - } - *ugly.last().unwrap() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_264() { - assert_eq!(Solution::nth_ugly_number(1), 1); - assert_eq!(Solution::nth_ugly_number(10), 12); - } -} diff --git a/src/solution/s0268_missing_number.rs b/src/solution/s0268_missing_number.rs deleted file mode 100644 index 63291ee0..00000000 --- a/src/solution/s0268_missing_number.rs +++ /dev/null @@ -1,46 +0,0 @@ -/** - * [268] Missing Number - * - * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. - * - * Example 1: - * - * - * Input: [3,0,1] - * Output: 2 - * - * - * Example 2: - * - * - * Input: [9,6,4,2,3,5,7,0,1] - * Output: 8 - * - * - * Note:
- * Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/missing-number/ -// discuss: https://leetcode.com/problems/missing-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn missing_number(nums: Vec) -> i32 { - ((nums.len() + 1) * nums.len()) as i32 / 2 - nums.into_iter().fold(0, |acc, v| acc + v) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_268() { - assert_eq!(Solution::missing_number(vec![3, 0, 1]), 2); - } -} diff --git a/src/solution/s0273_integer_to_english_words.rs b/src/solution/s0273_integer_to_english_words.rs deleted file mode 100644 index 123a1f9d..00000000 --- a/src/solution/s0273_integer_to_english_words.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [273] Integer to English Words - * - * Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 1. - * - * Example 1: - * - * - * Input: 123 - * Output: "One Hundred Twenty Three" - * - * - * Example 2: - * - * - * Input: 12345 - * Output: "Twelve Thousand Three Hundred Forty Five" - * - * Example 3: - * - * - * Input: 1234567 - * Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven" - * - * - * Example 4: - * - * - * Input: 1234567891 - * Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One" - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/integer-to-english-words/ -// discuss: https://leetcode.com/problems/integer-to-english-words/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// static digits: Vec<&str> = vec!["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]; -// static xteens: Vec<&str> = vec!["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventenn", "Eighteen", "Nineteen"]; -// static xtys: Vec<&str> = vec!["Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]; -// static hunderd: &str = "Hunderd"; -// static thousands: Vec<&str> = vec!["Thousand", "Million", "Billion"]; - -impl Solution { - pub fn number_to_words(num: i32) -> String { - "".to_owned() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_273() {} -} diff --git a/src/solution/s0274_h_index.rs b/src/solution/s0274_h_index.rs deleted file mode 100644 index b36f65a3..00000000 --- a/src/solution/s0274_h_index.rs +++ /dev/null @@ -1,53 +0,0 @@ -/** - * [274] H-Index - * - * 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. - * - * 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." - * - * Example: - * - * - * Input: citations = [3,0,6,1,5] - * Output: 3 - * Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had - * received 3, 0, 6, 1, 5 citations respectively. - * Since the researcher has 3 papers with at least 3 citations each and the remaining - * two with no more than 3 citations each, her h-index is 3. - * - * Note: If there are several possible values for h, the maximum one is taken as the h-index. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/h-index/ -// discuss: https://leetcode.com/problems/h-index/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn h_index(mut citations: Vec) -> i32 { - citations.sort_unstable(); - let mut hidx = 0; - for &v in citations.iter().rev() { - if v >= hidx + 1 { - hidx += 1; - } else { - break; - } - } - hidx - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_274() { - assert_eq!(Solution::h_index(vec![3, 0, 6, 1, 5]), 3); - } -} diff --git a/src/solution/s0275_h_index_ii.rs b/src/solution/s0275_h_index_ii.rs deleted file mode 100644 index 027ad02a..00000000 --- a/src/solution/s0275_h_index_ii.rs +++ /dev/null @@ -1,74 +0,0 @@ -/** - * [275] H-Index II - * - * Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. - * - * 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." - * - * Example: - * - * - * Input: citations = [0,1,3,5,6] - * Output: 3 - * Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had - * received 0, 1, 3, 5, 6 citations respectively. - * Since the researcher has 3 papers with at least 3 citations each and the remaining - * two with no more than 3 citations each, her h-index is 3. - * - * Note: - * - * If there are several possible values for h, the maximum one is taken as the h-index. - * - * Follow up: - * - * - * This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order. - * Could you solve it in logarithmic time complexity? - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/h-index-ii/ -// discuss: https://leetcode.com/problems/h-index-ii/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn h_index(citations: Vec) -> i32 { - if citations.is_empty() { - return 0; - } - let len = citations.len(); - let (mut low, mut high) = (0_usize, len - 1); - while low <= high { - let mid = low + (high - low) / 2; - if citations[mid] >= (len - mid) as i32 { - if mid == 0 { - break; - } - high = mid - 1; - } else { - low = mid + 1; - } - } - (len - low) as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_275() { - assert_eq!(Solution::h_index(vec![]), 0); - assert_eq!(Solution::h_index(vec![0]), 0); - assert_eq!(Solution::h_index(vec![11, 15]), 2); - assert_eq!(Solution::h_index(vec![1]), 1); - assert_eq!(Solution::h_index(vec![0, 1, 3, 5, 6]), 3); - assert_eq!(Solution::h_index(vec![0, 4, 4, 5, 6]), 4); - } -} diff --git a/src/solution/s0279_perfect_squares.rs b/src/solution/s0279_perfect_squares.rs deleted file mode 100644 index fe5f0a01..00000000 --- a/src/solution/s0279_perfect_squares.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [279] Perfect Squares - * - * Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. - * - * Example 1: - * - * - * Input: n = 12 - * Output: 3 - * Explanation: 12 = 4 + 4 + 4. - * - * Example 2: - * - * - * Input: n = 13 - * Output: 2 - * Explanation: 13 = 4 + 9. - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/perfect-squares/ -// discuss: https://leetcode.com/problems/perfect-squares/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// BFS -use std::collections::VecDeque; -impl Solution { - pub fn num_squares(n: i32) -> i32 { - if n < 1 { - return 0; - } - let mut deq = VecDeque::new(); - deq.push_back((1, n)); - while let Some((level, num)) = deq.pop_front() { - let mut base = 1; - while base * base <= num { - if base * base == num { - return level; - } - deq.push_back((level + 1, num - base * base)); - base += 1; - } - } - 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_279() { - assert_eq!(Solution::num_squares(13), 2); - assert_eq!(Solution::num_squares(12), 3); - } -} diff --git a/src/solution/s0282_expression_add_operators.rs b/src/solution/s0282_expression_add_operators.rs deleted file mode 100644 index 1c41367b..00000000 --- a/src/solution/s0282_expression_add_operators.rs +++ /dev/null @@ -1,61 +0,0 @@ -/** - * [282] Expression Add Operators - * - * 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. - * - * Example 1: - * - * - * Input: num = "123", target = 6 - * Output: ["1+2+3", "1*2*3"] - * - * - * Example 2: - * - * - * Input: num = "232", target = 8 - * Output: ["2*3+2", "2+3*2"] - * - * Example 3: - * - * - * Input: num = "105", target = 5 - * Output: ["1*0+5","10-5"] - * - * Example 4: - * - * - * Input: num = "00", target = 0 - * Output: ["0+0", "0-0", "0*0"] - * - * - * Example 5: - * - * - * Input: num = "3456237490", target = 9191 - * Output: [] - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/expression-add-operators/ -// discuss: https://leetcode.com/problems/expression-add-operators/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn add_operators(num: String, target: i32) -> Vec { - vec![] - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_282() {} -} diff --git a/src/solution/s0283_move_zeroes.rs b/src/solution/s0283_move_zeroes.rs deleted file mode 100644 index 6581bcaf..00000000 --- a/src/solution/s0283_move_zeroes.rs +++ /dev/null @@ -1,50 +0,0 @@ -/** - * [283] Move Zeroes - * - * 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. - * - * Example: - * - * - * Input: [0,1,0,3,12] - * Output: [1,3,12,0,0] - * - * Note: - * - *
    - * You must do this in-place without making a copy of the array. - * Minimize the total number of operations. - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/move-zeroes/ -// discuss: https://leetcode.com/problems/move-zeroes/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn move_zeroes(nums: &mut Vec) { - let mut last_none_zero = 0_usize; - for i in 0..nums.len() { - if nums[i] != 0 { - nums.swap(last_none_zero, i); - last_none_zero += 1; - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_283() { - let mut vec = vec![0, 1, 0, 3, 12]; - Solution::move_zeroes(&mut vec); - assert_eq!(vec, vec![1, 3, 12, 0, 0]); - } -} diff --git a/src/solution/s0287_find_the_duplicate_number.rs b/src/solution/s0287_find_the_duplicate_number.rs deleted file mode 100644 index cea65001..00000000 --- a/src/solution/s0287_find_the_duplicate_number.rs +++ /dev/null @@ -1,74 +0,0 @@ -/** - * [287] Find the Duplicate Number - * - * 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. - * - * Example 1: - * - * - * Input: [1,3,4,2,2] - * Output: 2 - * - * - * Example 2: - * - * - * Input: [3,1,3,4,2] - * Output: 3 - * - * Note: - * - *
    - * You must not modify the array (assume the array is read only). - * You must use only constant, O(1) extra space. - * Your runtime complexity should be less than O(n^2). - * There is only one duplicate number in the array, but it could be repeated more than once. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/find-the-duplicate-number/ -// discuss: https://leetcode.com/problems/find-the-duplicate-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// 假如把值看做 next node 的下标, 那么: -// 从 0 出发不会回到 0 -// 一定有环, 因为 1-n 全部落在下标范围 [0, n] 中 -// 从 0 遍历经过的环中, 一定存在重复数字 x, 且 x 就是入环点的下标: -// 1.从 0 走到入环点, 入环点的前驱值为 x; 2.入环点在环上的前驱值也是 x -// 由于我们不可能回到 0, 因此这两个节点下标不同, x 即为要找的重复数字 -impl Solution { - pub fn find_duplicate(nums: Vec) -> i32 { - let mut slow: usize = nums[0] as usize; - let mut fast: usize = nums[nums[0] as usize] as usize; - // util slow meet fast - while slow != fast { - slow = nums[slow] as usize; - fast = nums[nums[fast] as usize] as usize; - } - - fast = 0_usize; - while slow != fast { - fast = nums[fast] as usize; - slow = nums[slow] as usize; - } - slow as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_287() { - assert_eq!(Solution::find_duplicate(vec![1, 3, 4, 2, 2]), 2); - assert_eq!(Solution::find_duplicate(vec![3, 1, 3, 4, 2]), 3); - assert_eq!(Solution::find_duplicate(vec![1, 2, 3, 4, 5, 5]), 5); - assert_eq!(Solution::find_duplicate(vec![5, 1, 2, 3, 4, 5]), 5); - } -} diff --git a/src/solution/s0289_game_of_life.rs b/src/solution/s0289_game_of_life.rs deleted file mode 100644 index 53d34623..00000000 --- a/src/solution/s0289_game_of_life.rs +++ /dev/null @@ -1,118 +0,0 @@ -/** - * [289] Game of Life - * - * According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." - * - * Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): - * - *
    - * Any live cell with fewer than two live neighbors dies, as if caused by under-population. - * Any live cell with two or three live neighbors lives on to the next generation. - * Any live cell with more than three live neighbors dies, as if by over-population.. - * Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. - *
- * - * Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. - * - * Example: - * - * - * Input: - * [ - * [0,1,0], - * [0,0,1], - * [1,1,1], - * [0,0,0] - * ] - * Output: - * [ - * [0,0,0], - * [1,0,1], - * [0,1,1], - * [0,1,0] - * ] - * - * - * Follow up: - * - *
    - * Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells. - * In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems? - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/game-of-life/ -// discuss: https://leetcode.com/problems/game-of-life/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// in-place: 1: live->live, 0: die->die, 2: die->live, 3: live->die -impl Solution { - pub fn game_of_life(board: &mut Vec>) { - let (height, width) = (board.len(), board[0].len()); - let neighbors = vec![ - (-1, -1), - (-1, 0), - (-1, 1), - (0, -1), - (0, 1), - (1, -1), - (1, 0), - (1, 1), - ]; - for i in 0..height { - for j in 0..width { - let mut live = 0; - for offset in neighbors.iter() { - if (offset.0 < 0 && i == 0) - || (offset.0 > 0 && i == height - 1) - || (offset.1 < 0 && j == 0) - || (offset.1 > 0 && j == width - 1) - { - continue; - } - let v = board[(i as i32 + offset.0) as usize][(j as i32 + offset.1) as usize]; - if v == 1 || v == 3 { - live += 1; - } - } - if board[i][j] == 1 && (live < 2 || live > 3) { - // go die - board[i][j] = 3; - } else if board[i][j] == 0 && live == 3 { - // go live - board[i][j] = 2; - } - } - } - - for i in 0..height { - for j in 0..width { - if board[i][j] == 2 { - board[i][j] = 1; - } else if board[i][j] == 3 { - board[i][j] = 0; - } - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_289() { - let mut test = vec![vec![0, 1, 0], vec![0, 0, 1], vec![1, 1, 1], vec![0, 0, 0]]; - Solution::game_of_life(&mut test); - assert_eq!( - test, - vec![vec![0, 0, 0], vec![1, 0, 1], vec![0, 1, 1], vec![0, 1, 0],] - ); - } -} diff --git a/src/solution/s0290_word_pattern.rs b/src/solution/s0290_word_pattern.rs deleted file mode 100644 index c758f352..00000000 --- a/src/solution/s0290_word_pattern.rs +++ /dev/null @@ -1,86 +0,0 @@ -/** - * [290] Word Pattern - * - * Given a pattern and a string str, find if str follows the same pattern. - * - * Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. - * - * Example 1: - * - * - * Input: pattern = "abba", str = "dog cat cat dog" - * Output: true - * - * Example 2: - * - * - * Input:pattern = "abba", str = "dog cat cat fish" - * Output: false - * - * Example 3: - * - * - * Input: pattern = "aaaa", str = "dog cat cat dog" - * Output: false - * - * Example 4: - * - * - * Input: pattern = "abba", str = "dog dog dog dog" - * Output: false - * - * Notes:
- * You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/word-pattern/ -// discuss: https://leetcode.com/problems/word-pattern/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::HashMap; -impl Solution { - pub fn word_pattern(pattern: String, s: String) -> bool { - let mut p2s = HashMap::new(); - let mut s2p = HashMap::new(); - let mut s_iter = s.split(" "); - let mut p_iter = pattern.chars(); - loop { - match (s_iter.next(), p_iter.next()) { - (Some(sub), Some(ch)) => { - if *p2s.entry(ch).or_insert(sub) != sub || *s2p.entry(sub).or_insert(ch) != ch { - return false; - } - } - (None, None) => break, - _ => return false, - } - } - true - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_290() { - assert_eq!( - Solution::word_pattern("abba".to_owned(), "dog cat cat dog".to_owned()), - true - ); - assert_eq!( - Solution::word_pattern("aaaa".to_owned(), "dog cat cat dog".to_owned()), - false - ); - assert_eq!( - Solution::word_pattern("abba".to_owned(), "dog cat cat fish".to_owned()), - false - ); - } -} diff --git a/src/solution/s0292_nim_game.rs b/src/solution/s0292_nim_game.rs deleted file mode 100644 index 4c46505c..00000000 --- a/src/solution/s0292_nim_game.rs +++ /dev/null @@ -1,40 +0,0 @@ -/** - * [292] Nim Game - * - * 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. - * - * 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. - * - * Example: - * - * - * Input: 4 - * Output: false - * Explanation: If there are 4 stones in the heap, then you will never win the game; - * No matter 1, 2, or 3 stones you remove, the last stone will always be - * removed by your friend. - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/nim-game/ -// discuss: https://leetcode.com/problems/nim-game/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn can_win_nim(n: i32) -> bool { - n % 4 != 0 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_292() { - assert_eq!(Solution::can_win_nim(4), false); - } -} diff --git a/src/solution/s0295_find_median_from_data_stream.rs b/src/solution/s0295_find_median_from_data_stream.rs deleted file mode 100644 index 02dc5331..00000000 --- a/src/solution/s0295_find_median_from_data_stream.rs +++ /dev/null @@ -1,136 +0,0 @@ -/** - * [295] Find Median from Data Stream - * - * Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. - * For example, - * - * [2,3,4], the median is 3 - * - * [2,3], the median is (2 + 3) / 2 = 2.5 - * - * Design a data structure that supports the following two operations: - * - * - * void addNum(int num) - Add a integer number from the data stream to the data structure. - * double findMedian() - Return the median of all elements so far. - * - * - * - * - * Example: - * - * - * addNum(1) - * addNum(2) - * findMedian() -> 1.5 - * addNum(3) - * findMedian() -> 2 - * - * - * - * - * Follow up: - * - *
    - * If all integer numbers from the stream are between 0 and 100, how would you optimize it? - * If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it? - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/find-median-from-data-stream/ -// discuss: https://leetcode.com/problems/find-median-from-data-stream/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cmp::Ordering; -use std::collections::BinaryHeap; -#[derive(Eq, PartialEq)] -struct Invert { - value: i32, -} - -impl Ord for Invert { - fn cmp(&self, other: &Invert) -> Ordering { - other.value.cmp(&self.value) - } -} - -impl PartialOrd for Invert { - fn partial_cmp(&self, other: &Invert) -> Option { - Some(self.cmp(other)) - } -} - -struct MedianFinder { - head: BinaryHeap, - tail: BinaryHeap, - count: i32, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl MedianFinder { - /** initialize your data structure here. */ - fn new() -> Self { - MedianFinder { - head: BinaryHeap::new(), - tail: BinaryHeap::new(), - count: 0, - } - } - - fn add_num(&mut self, num: i32) { - self.count += 1; - if self.head.is_empty() || num > self.head.peek().unwrap().value { - self.head.push(Invert { value: num }); - } else { - self.tail.push(num); - } - // balance - if self.head.len() > self.tail.len() + 1 { - self.tail.push(self.head.pop().unwrap().value); - } else if self.head.len() + 1 < self.tail.len() { - self.head.push(Invert { - value: self.tail.pop().unwrap(), - }); - } - } - - fn find_median(&self) -> f64 { - if self.head.len() > self.tail.len() { - self.head.peek().unwrap().value as f64 - } else if self.head.len() < self.tail.len() { - *self.tail.peek().unwrap() as f64 - } else { - (self.head.peek().unwrap().value as f64 + *self.tail.peek().unwrap() as f64) / 2.0 - } - } -} - -/** - * Your MedianFinder object will be instantiated and called as such: - * let obj = MedianFinder::new(); - * obj.add_num(num); - * let ret_2: f64 = obj.find_median(); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_295() { - let mut obj = MedianFinder::new(); - obj.add_num(1); - obj.add_num(2); - assert_eq!(obj.find_median(), 1.5); - obj.add_num(3); - assert_eq!(obj.find_median(), 2_f64); - } -} diff --git a/src/solution/s0299_bulls_and_cows.rs b/src/solution/s0299_bulls_and_cows.rs deleted file mode 100644 index 08525c71..00000000 --- a/src/solution/s0299_bulls_and_cows.rs +++ /dev/null @@ -1,80 +0,0 @@ -/** - * [299] Bulls and Cows - * - * You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number. - * - * Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows. - * - * Please note that both secret number and friend's guess may contain duplicate digits. - * - * Example 1: - * - * - * Input: secret = "1807", guess = "7810" - * - * Output: "1A3B" - * - * Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7. - * - * Example 2: - * - * - * Input: secret = "1123", guess = "0111" - * - * Output: "1A1B" - * - * Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow. - * - * Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal. - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/bulls-and-cows/ -// discuss: https://leetcode.com/problems/bulls-and-cows/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn get_hint(secret: String, guess: String) -> String { - let mut bulls = 0; - let mut cows = 0; - let mut s_iter = secret.chars(); - let mut g_iter = guess.chars(); - let mut bucket = vec![0; 10]; - let mut non_match = vec![]; - while let (Some(s), Some(g)) = (s_iter.next(), g_iter.next()) { - if s == g { - bulls += 1; - } else { - bucket[s.to_digit(10).unwrap() as usize] += 1; - non_match.push(g.to_digit(10).unwrap() as usize); - } - } - for &idx in non_match.iter() { - if bucket[idx] > 0 { - cows += 1; - bucket[idx] -= 1; - } - } - format!("{}A{}B", bulls, cows) - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_299() { - assert_eq!( - Solution::get_hint("1807".to_owned(), "7810".to_owned()), - "1A3B".to_owned() - ); - assert_eq!( - Solution::get_hint("1123".to_owned(), "0111".to_owned()), - "1A1B".to_owned() - ); - } -} diff --git a/src/solution/s0300_longest_increasing_subsequence.rs b/src/solution/s0300_longest_increasing_subsequence.rs deleted file mode 100644 index c0b7eb27..00000000 --- a/src/solution/s0300_longest_increasing_subsequence.rs +++ /dev/null @@ -1,57 +0,0 @@ -/** - * [300] Longest Increasing Subsequence - * - * Given an unsorted array of integers, find the length of longest increasing subsequence. - * - * Example: - * - * - * Input: [10,9,2,5,3,7,101,18] - * Output: 4 - * Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. - * - * Note: - * - * - * There may be more than one LIS combination, it is only necessary for you to return the length. - * Your algorithm should run in O(n^2) complexity. - * - * - * Follow up: Could you improve it to O(n log n) time complexity? - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/longest-increasing-subsequence/ -// discuss: https://leetcode.com/problems/longest-increasing-subsequence/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -// N^2, DP: L[i] = max(1 + L[j]) for j in [0, i) and nums[j] < nums[i] -// 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 -impl Solution { - pub fn length_of_lis(nums: Vec) -> i32 { - let mut incr = Vec::new(); - for &num in nums.iter() { - if let Err(idx) = incr.binary_search(&num) { - if idx >= incr.len() { - incr.push(num); - } else { - incr[idx] = num; - } - } - } - incr.len() as i32 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_300() { - assert_eq!(Solution::length_of_lis(vec![10, 9, 2, 5, 3, 7, 101, 18]), 4); - } -} diff --git a/src/solution/s0301_remove_invalid_parentheses.rs b/src/solution/s0301_remove_invalid_parentheses.rs deleted file mode 100644 index 2cec757c..00000000 --- a/src/solution/s0301_remove_invalid_parentheses.rs +++ /dev/null @@ -1,131 +0,0 @@ -/** - * [301] Remove Invalid Parentheses - * - * Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. - * - * Note: The input string may contain letters other than the parentheses ( and ). - * - * Example 1: - * - * - * Input: "()())()" - * Output: ["()()()", "(())()"] - * - * - * Example 2: - * - * - * Input: "(a)())()" - * Output: ["(a)()()", "(a())()"] - * - * - * Example 3: - * - * - * Input: ")(" - * Output: [""] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/remove-invalid-parentheses/ -// discuss: https://leetcode.com/problems/remove-invalid-parentheses/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// 1. Calculate the number of misplaced left parenthese and right parenthese -// 2. DFS the string to find the all possible removing policy -use std::collections::HashSet; -impl Solution { - pub fn remove_invalid_parentheses(s: String) -> Vec { - let (mut left, mut right) = (0, 0); - let mut chs: Vec = s.chars().collect(); - for &c in chs.iter() { - if c == '(' { - left += 1; - } else if c == ')' { - if left > 0 { - left -= 1; - } else { - right += 1; - } - } - } - - // Now, the number of left and right parentheses are 'left' and 'right' - let mut res: HashSet = HashSet::new(); - let mut seed: Vec = Vec::new(); - Solution::helper(&chs, 0, 0, left, right, &mut seed, &mut res); - res.into_iter().collect() - } - - fn helper( - chs: &Vec, - idx: usize, - left: i32, - l_remain: i32, - r_remain: i32, - exp: &mut Vec, - res: &mut HashSet, - ) { - if idx >= chs.len() { - if left == 0 { - res.insert(exp.iter().collect()); - } - return; - } - if chs[idx] == '(' { - if l_remain > 0 { - Solution::helper( - chs, - idx + 1, - left, - l_remain - 1, - r_remain, - &mut exp.clone(), - res, - ); - } - exp.push('('); - Solution::helper(chs, idx + 1, left + 1, l_remain, r_remain, exp, res); - } else if chs[idx] == ')' { - if r_remain > 0 { - Solution::helper( - chs, - idx + 1, - left, - l_remain, - r_remain - 1, - &mut exp.clone(), - res, - ); - } - if left > 0 { - exp.push(')'); - Solution::helper(chs, idx + 1, left - 1, l_remain, r_remain, exp, res); - } - } else { - exp.push(chs[idx]); - Solution::helper(chs, idx + 1, left, l_remain, r_remain, exp, res); - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_301() { - assert_eq!( - Solution::remove_invalid_parentheses("()())()".to_owned()), - vec_string!["(())()", "()()()"] - ); - assert_eq!( - Solution::remove_invalid_parentheses("(a)())()".to_owned()), - vec_string!["(a)()()", "(a())()"] - ); - } -} diff --git a/src/solution/s0303_range_sum_query_immutable.rs b/src/solution/s0303_range_sum_query_immutable.rs deleted file mode 100644 index c56f8ae9..00000000 --- a/src/solution/s0303_range_sum_query_immutable.rs +++ /dev/null @@ -1,74 +0,0 @@ -/** - * [303] Range Sum Query - Immutable - * - * Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. - * - * Example:
- * - * Given nums = [-2, 0, 3, -5, 2, -1] - * - * sumRange(0, 2) -> 1 - * sumRange(2, 5) -> -1 - * sumRange(0, 5) -> -3 - * - * - * - * Note:
- *
    - * You may assume that the array does not change. - * There are many calls to sumRange function. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/range-sum-query-immutable/ -// discuss: https://leetcode.com/problems/range-sum-query-immutable/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -struct NumArray { - nums: Vec, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl NumArray { - fn new(nums: Vec) -> Self { - let mut res = 0; - let mut vec = Vec::with_capacity(nums.len()); - for &num in nums.iter() { - res += num; - vec.push(res); - } - NumArray { nums: vec } - } - - fn sum_range(&self, i: i32, j: i32) -> i32 { - let (i, j) = (i as usize, j as usize); - self.nums[j] - if i > 0 { self.nums[i - 1] } else { 0 } - } -} - -/** - * Your NumArray object will be instantiated and called as such: - * let obj = NumArray::new(nums); - * let ret_1: i32 = obj.sum_range(i, j); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_303() { - let mut nums = NumArray::new(vec![-2, 0, 3, -5, 2, -1]); - assert_eq!(nums.sum_range(0, 2), 1); - assert_eq!(nums.sum_range(2, 5), -1); - assert_eq!(nums.sum_range(0, 5), -3); - } -} diff --git a/src/solution/s0304_range_sum_query_2d_immutable.rs b/src/solution/s0304_range_sum_query_2d_immutable.rs deleted file mode 100644 index 42a0f41f..00000000 --- a/src/solution/s0304_range_sum_query_2d_immutable.rs +++ /dev/null @@ -1,124 +0,0 @@ -/** - * [304] Range Sum Query 2D - Immutable - * - * Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). - * - * - * Range Sum Query 2D
- * The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8. - * - * - * Example:
- * - * Given matrix = [ - * [3, 0, 1, 4, 2], - * [5, 6, 3, 2, 1], - * [1, 2, 0, 1, 5], - * [4, 1, 0, 1, 7], - * [1, 0, 3, 0, 5] - * ] - * - * sumRegion(2, 1, 4, 3) -> 8 - * sumRegion(1, 1, 2, 2) -> 11 - * sumRegion(1, 2, 2, 4) -> 12 - * - * - * - * Note:
- *
    - * You may assume that the matrix does not change. - * There are many calls to sumRegion function. - * You may assume that row1 ≤ row2 and col1 ≤ col2. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/range-sum-query-2d-immutable/ -// discuss: https://leetcode.com/problems/range-sum-query-2d-immutable/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -struct NumMatrix { - cache: Vec>, -} - -/** region[2, 2, 3, 4] = - * x x \ \ \ . square[3,4] - square[1,4] - square[3,1] + square[1,1] - * x x \ \ \ . - * / / o o o . - * / / o o o . - * . . . . . . - * . . . . . . - */ -impl NumMatrix { - fn new(matrix: Vec>) -> Self { - if matrix.is_empty() || matrix[0].is_empty() { - return NumMatrix { - cache: vec![vec![]], - }; - } - let (x_max, y_max) = (matrix.len(), matrix[0].len()); - let mut cache = vec![vec![0; y_max]; x_max]; - for x in 0..x_max { - for y in 0..y_max { - cache[x][y] = matrix[x][y] - + if y > 0 { cache[x][y - 1] } else { 0 } - + if x > 0 { cache[x - 1][y] } else { 0 } - - if x > 0 && y > 0 { - cache[x - 1][y - 1] - } else { - 0 - } - } - } - NumMatrix { cache: cache } - } - - fn sum_region(&self, row1: i32, col1: i32, row2: i32, col2: i32) -> i32 { - let (row1, col1, row2, col2) = (row1 as usize, col1 as usize, row2 as usize, col2 as usize); - self.cache[row2][col2] - - if row1 > 0 { - self.cache[row1 - 1][col2] - } else { - 0 - } - - if col1 > 0 { - self.cache[row2][col1 - 1] - } else { - 0 - } - + if row1 > 0 && col1 > 0 { - self.cache[row1 - 1][col1 - 1] - } else { - 0 - } - } -} - -/** - * Your NumMatrix object will be instantiated and called as such: - * let obj = NumMatrix::new(matrix); - * let ret_1: i32 = obj.sum_region(row1, col1, row2, col2); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_304() { - let matrix = NumMatrix::new(vec![ - vec![3, 0, 1, 4, 2], - vec![5, 6, 3, 2, 1], - vec![1, 2, 0, 1, 5], - vec![4, 1, 0, 1, 7], - vec![1, 0, 3, 0, 5], - ]); - assert_eq!(matrix.sum_region(1, 1, 2, 2), 11); - assert_eq!(matrix.sum_region(2, 1, 4, 3), 8); - assert_eq!(matrix.sum_region(1, 2, 2, 4), 12); - } -} diff --git a/src/solution/s0306_additive_number.rs b/src/solution/s0306_additive_number.rs deleted file mode 100644 index 38f6c0b2..00000000 --- a/src/solution/s0306_additive_number.rs +++ /dev/null @@ -1,113 +0,0 @@ -/** - * [306] Additive Number - * - * Additive number is a string whose digits can form additive sequence. - * - * A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. - * - * Given a string containing only digits '0'-'9', write a function to determine if it's an additive number. - * - * Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid. - * - * Example 1: - * - * - * Input: "112358" - * Output: true - * Explanation: The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. - * 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8 - * - * - * Example 2: - * - * - * Input: "199100199" - * Output: true - * Explanation: The additive sequence is: 1, 99, 100, 199. - * 1 + 99 = 100, 99 + 100 = 199 - * - * Follow up:
- * How would you handle overflow for very large input integers? - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/additive-number/ -// discuss: https://leetcode.com/problems/additive-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -// first_cut second_cut third_cut -// V V V -// 1 99 100 199 -impl Solution { - pub fn is_additive_number(num: String) -> bool { - let mut chs: Vec = num.chars().map(|c| c.to_digit(10).unwrap()).collect(); - let mut num1 = 0; - let len = chs.len(); - // first cut - for i in 0..(len / 2 + 1) { - num1 = num1 * 10 + chs[i]; - if Solution::second_cut(i + 1, len, num1, &chs) { - return true; - } - if num1 == 0 { - break; - } - } - false - } - - fn second_cut(from: usize, len: usize, num1: u32, chs: &Vec) -> bool { - let mut num2 = 0; - for i in from..len { - num2 = num2 * 10 + chs[i]; - if Solution::third_cut(i + 1, len, num1, num2, chs, false) { - return true; - } - if num2 == 0 { - break; - } - } - false - } - - fn third_cut( - from: usize, - len: usize, - num1: u32, - num2: u32, - chs: &Vec, - found: bool, - ) -> bool { - if found && from >= len { - return true; - } - let mut num3 = 0; - for i in from..len { - num3 = num3 * 10 + chs[i]; - if num3 == num2 + num1 { - if Solution::third_cut(i + 1, len, num2, num3, chs, true) { - return true; - } - } else if num3 == 0 || num3 > num1 + num2 { - break; - } - } - false - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_306() { - assert_eq!(Solution::is_additive_number("112358".to_owned()), true); - assert_eq!(Solution::is_additive_number("199100199".to_owned()), true); - assert_eq!(Solution::is_additive_number("1991001990".to_owned()), false); - assert_eq!(Solution::is_additive_number("1023".to_owned()), false); - } -} diff --git a/src/solution/s0307_range_sum_query_mutable.rs b/src/solution/s0307_range_sum_query_mutable.rs deleted file mode 100644 index bbaac119..00000000 --- a/src/solution/s0307_range_sum_query_mutable.rs +++ /dev/null @@ -1,151 +0,0 @@ -/** - * [307] Range Sum Query - Mutable - * - * Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. - * - * The update(i, val) function modifies nums by updating the element at index i to val. - * - * Example: - * - * - * Given nums = [1, 3, 5] - * - * sumRange(0, 2) -> 9 - * update(1, 2) - * sumRange(0, 2) -> 8 - * - * - * Note: - * - *
    - * The array is only modifiable by the update function. - * You may assume the number of calls to update and sumRange function is distributed evenly. - *
- * - */ -pub struct Solution {} - -// Segement Tree -// -// N[0:6] -// / \ -// / \ -// N[0:3] N[4:6] -// / \ / \ -// N[0:1] N[2:3] N[4:5] N[6] -// / \ / \ / \ -// N[0] N[1] N[2] N[3] N[4] N[5] -// -// problem: https://leetcode.com/problems/range-sum-query-mutable/ -// discuss: https://leetcode.com/problems/range-sum-query-mutable/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -struct NumArray { - tree: Vec, - n: usize, -} - -/** - * `&self` means the method takes an immutable reference. - * If you need a mutable reference, change it to `&mut self` instead. - */ -impl NumArray { - fn new(nums: Vec) -> Self { - let n = nums.len(); - let mut tree = vec![0; 4 * n]; - if n > 0 { - NumArray::build(1, 0, n - 1, &mut tree, &nums); - } - NumArray { tree: tree, n: n } - } - - fn update(&mut self, i: i32, val: i32) { - NumArray::update_internal(i as usize, val, 1, 0, self.n - 1, &mut self.tree); - } - - fn sum_range(&self, i: i32, j: i32) -> i32 { - NumArray::sum(1, 0, self.n - 1, i as usize, j as usize, &self.tree) - } - - fn build(node: usize, start: usize, end: usize, tree: &mut Vec, nums: &Vec) { - if start == end { - tree[node] = nums[start]; - } else { - let mid = (start + end) / 2; - NumArray::build(2 * node, start, mid, tree, nums); - NumArray::build(2 * node + 1, mid + 1, end, tree, nums); - tree[node] = tree[2 * node] + tree[2 * node + 1]; - } - } - - fn update_internal( - i: usize, - val: i32, - node: usize, - start: usize, - end: usize, - tree: &mut Vec, - ) { - if start == end { - tree[node] = val; - } else { - let mid = (start + end) / 2; - if i <= mid { - NumArray::update_internal(i, val, 2 * node, start, mid, tree); - } else { - NumArray::update_internal(i, val, 2 * node + 1, mid + 1, end, tree); - } - tree[node] = tree[2 * node] + tree[2 * node + 1]; - } - } - - fn sum( - node: usize, - start: usize, - end: usize, - left: usize, - right: usize, - tree: &Vec, - ) -> i32 { - if right < start || left > end { - // not in range - 0 - } else if left <= start && end <= right { - // completely in range - tree[node] - } else { - // partially in range - let mid = (start + end) / 2; - NumArray::sum(2 * node, start, mid, left, right, tree) - + NumArray::sum(2 * node + 1, mid + 1, end, left, right, tree) - } - } -} - -/** - * Your NumArray object will be instantiated and called as such: - * let obj = NumArray::new(nums); - * obj.update(i, val); - * let ret_2: i32 = obj.sum_range(i, j); - */ - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_307() { - let _empty = NumArray::new(vec![]); - let mut tree = NumArray::new(vec![1, 1, 1, 1, 1, 1, 1, 1, 1, 1]); - assert_eq!(tree.sum_range(0, 6), 7); - tree.update(0, 2); - assert_eq!(tree.sum_range(0, 6), 8); - tree.update(1, 2); - assert_eq!(tree.sum_range(0, 2), 5); - tree.update(6, 10); - assert_eq!(tree.sum_range(6, 6), 10); - } -} diff --git a/src/solution/s0309_best_time_to_buy_and_sell_stock_with_cooldown.rs b/src/solution/s0309_best_time_to_buy_and_sell_stock_with_cooldown.rs deleted file mode 100644 index 6f3e911d..00000000 --- a/src/solution/s0309_best_time_to_buy_and_sell_stock_with_cooldown.rs +++ /dev/null @@ -1,79 +0,0 @@ -/** - * [309] Best Time to Buy and Sell Stock with Cooldown - * - * Say you have an array for which the i^th element is the price of a given stock on day i. - * - * Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions: - * - * - * You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). - * After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day) - * - * - * Example: - * - * - * Input: [1,2,3,0,2] - * Output: 3 - * Explanation: transactions = [buy, sell, cooldown, buy, sell] - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/ -// discuss: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -dp[i]: max profit with selling at day i -dp2[i]: max profit till day i - -dp[i] = max(dp[i-1] + p[i] - p[i-1], dp2[i-2], dp2[i-3] + p[i] - p[i-1]) -*/ -impl Solution { - pub fn max_profit(prices: Vec) -> i32 { - if prices.len() < 2 { - return 0; - } - if prices.len() == 2 { - return i32::max(0, prices[1] - prices[0]); - } - let mut dp = vec![0; prices.len()]; - let mut dp2 = vec![0; prices.len()]; - let mut max = 0; - dp[0] = 0; - dp2[0] = 0; - dp[1] = prices[1] - prices[0]; - dp2[1] = i32::max(dp2[0], dp[1]); - dp[2] = i32::max(prices[2] - prices[1], prices[2] - prices[0]); - dp2[2] = i32::max(dp2[1], dp[2]); - for i in 3..prices.len() { - dp[i] = i32::max( - dp[i - 1] + prices[i] - prices[i - 1], - i32::max(dp2[i - 2], dp2[i - 3] + prices[i] - prices[i - 1]), - ); - dp2[i] = i32::max(dp2[i - 1], dp[i]); - } - let mut temp = 0; - for &m in dp.iter() { - if m > temp { - temp = m; - } - } - temp - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_309() { - assert_eq!(Solution::max_profit(vec![1, 2, 3, 0, 2]), 3); - assert_eq!(Solution::max_profit(vec![4, 2, 7, 1, 11]), 10); - } -} diff --git a/src/solution/s0310_minimum_height_trees.rs b/src/solution/s0310_minimum_height_trees.rs deleted file mode 100644 index 4141273c..00000000 --- a/src/solution/s0310_minimum_height_trees.rs +++ /dev/null @@ -1,110 +0,0 @@ -/** - * [310] Minimum Height Trees - * - * For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels. - * - * Format
- * The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels). - * - * You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. - * - * Example 1 : - * - * - * Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]] - * - * 0 - * | - * 1 - * / \ - * 2 3 - * - * Output: [1] - * - * - * Example 2 : - * - * - * Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]] - * - * 0 1 2 - * \ | / - * 3 - * | - * 4 - * | - * 5 - * - * Output: [3, 4] - * - * Note: - * - * - * According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.” - * The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/minimum-height-trees/ -// discuss: https://leetcode.com/problems/minimum-height-trees/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::mem; -impl Solution { - pub fn find_min_height_trees(n: i32, edges: Vec>) -> Vec { - let n = n as usize; - let mut matrix: Vec> = vec![vec![]; n]; - for edge in edges.iter() { - matrix[edge[0] as usize].push(edge[1] as usize); - matrix[edge[1] as usize].push(edge[0] as usize); - } - let mut count = n; - let mut la: Vec = vec![]; - let mut lb: Vec = vec![]; - for i in 0..n { - if matrix[i].len() <= 1 { - la.push(i); - } - } - while count > 2 { - count -= la.len(); - for &i in la.iter() { - let j = matrix[i][0]; - let idx = matrix[j].iter().position(|&r| r == i).unwrap(); - matrix[j].remove(idx); - if matrix[j].len() == 1 { - lb.push(j); - } - } - la.clear(); - mem::swap(&mut la, &mut lb); - } - la.into_iter().map(|i| i as i32).collect() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_310() { - assert_eq!( - Solution::find_min_height_trees(4, vec![vec![1, 0], vec![1, 2], vec![1, 3]]), - vec![1] - ); - assert_eq!( - Solution::find_min_height_trees( - 6, - vec![vec![0, 3], vec![1, 3], vec![2, 3], vec![4, 3], vec![5, 4]] - ), - vec![3, 4] - ); - assert_eq!(Solution::find_min_height_trees(1, vec![]), vec![0]); - } -} diff --git a/src/solution/s0312_burst_balloons.rs b/src/solution/s0312_burst_balloons.rs deleted file mode 100644 index f8833b5e..00000000 --- a/src/solution/s0312_burst_balloons.rs +++ /dev/null @@ -1,108 +0,0 @@ -/** - * [312] Burst Balloons - * - * Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent. - * - * Find the maximum coins you can collect by bursting the balloons wisely. - * - * Note: - * - * - * You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them. - * 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100 - * - * - * Example: - * - * - * Input: [3,1,5,8] - * Output: 167 - * Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] - * coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/burst-balloons/ -// discuss: https://leetcode.com/problems/burst-balloons/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -/* -The key idea is, for a sequence of balloon, select a balloon to be the last one to be bursted: - -max of [1 . a b c d e f . 1] - - ^ say we select 'c' as the last balloon to burst, then: - -= - max of [1 . a b . c] + - - max of [c . d e f . 1] + - - 1 * c * 1 - -Then we can use memorize to record the max of every sub sequence -*/ -impl Solution { - pub fn max_coins(nums: Vec) -> i32 { - if nums.is_empty() { - return 0; - } - let mut coins = vec![0; nums.len() + 2]; - let mut len = 0_usize; - // filter out zeros - for &num in nums.iter() { - if num != 0 { - len += 1; - coins[len] = num; - } - } - coins[0] = 1; - coins[len + 1] = 1; - - let mut memo = vec![vec![0; len + 1]; len + 1]; - Solution::max_subrange(&coins, 1, len, &mut memo) - } - - fn max_subrange(coins: &Vec, start: usize, end: usize, memo: &mut Vec>) -> i32 { - if memo[start][end] != 0 { - return memo[start][end]; - } - if start == end { - memo[start][end] = coins[start - 1] * coins[start] * coins[start + 1]; - return memo[start][end]; - } - let mut max = 0; - for i in start..end + 1 { - let left_max = if i > start { - Solution::max_subrange(coins, start, i - 1, memo) - } else { - 0 - }; - let right_max = if i < end { - Solution::max_subrange(coins, i + 1, end, memo) - } else { - 0 - }; - max = i32::max( - max, - left_max + right_max + coins[i] * coins[start - 1] * coins[end + 1], - ); - } - memo[start][end] = max; - return memo[start][end]; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_312() { - assert_eq!(Solution::max_coins(vec![3, 1, 5, 8]), 167); - } -} diff --git a/src/solution/s0313_super_ugly_number.rs b/src/solution/s0313_super_ugly_number.rs deleted file mode 100644 index bf99bcc8..00000000 --- a/src/solution/s0313_super_ugly_number.rs +++ /dev/null @@ -1,94 +0,0 @@ -/** - * [313] Super Ugly Number - * - * Write a program to find the n^th super ugly number. - * - * Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. - * - * Example: - * - * - * Input: n = 12, primes = [2,7,13,19] - * Output: 32 - * Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 - * super ugly numbers given primes = [2,7,13,19] of size 4. - * - * Note: - * - * - * 1 is a super ugly number for any given primes. - * The given numbers in primes are in ascending order. - * 0 < k ≤ 100, 0 < n ≤ 10^6, 0 < primes[i] < 1000. - * The n^th super ugly number is guaranteed to fit in a 32-bit signed integer. - * - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/super-ugly-number/ -// discuss: https://leetcode.com/problems/super-ugly-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::cmp::Ordering; -use std::collections::BinaryHeap; -#[derive(Eq, PartialEq)] -struct Invert { - base: i32, - idx: usize, - value: i32, -} - -impl Ord for Invert { - fn cmp(&self, other: &Invert) -> Ordering { - other.value.cmp(&self.value) - } -} - -impl PartialOrd for Invert { - fn partial_cmp(&self, other: &Invert) -> Option { - Some(self.cmp(other)) - } -} - -impl Solution { - pub fn nth_super_ugly_number(n: i32, primes: Vec) -> i32 { - let mut vec = vec![1; 1]; - let mut heap: BinaryHeap = BinaryHeap::new(); - for &prime in primes.iter() { - heap.push(Invert { - base: prime, - idx: 0, - value: prime, - }); - } - for _ in 0..n - 1 { - let mut min = 0; - if let Some(num) = heap.peek() { - min = num.value; - } - vec.push(min); - while heap.peek().unwrap().value == min { - let p = heap.pop().unwrap(); - heap.push(Invert { - base: p.base, - idx: p.idx + 1, - value: p.base * vec[p.idx + 1], - }); - } - } - *vec.last().unwrap() - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_313() { - assert_eq!(Solution::nth_super_ugly_number(12, vec![2, 7, 13, 19]), 32); - } -} diff --git a/src/solution/s0509_fibonacci_number.rs b/src/solution/s0509_fibonacci_number.rs deleted file mode 100644 index 47a9b420..00000000 --- a/src/solution/s0509_fibonacci_number.rs +++ /dev/null @@ -1,78 +0,0 @@ -/** - * [1013] Fibonacci Number - * - * 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, - * - * - * F(0) = 0, F(1) = 1 - * F(N) = F(N - 1) + F(N - 2), for N > 1. - * - * - * Given N, calculate F(N). - * - * - * - * Example 1: - * - * - * Input: 2 - * Output: 1 - * Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. - * - * - * Example 2: - * - * - * Input: 3 - * Output: 2 - * Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. - * - * - * Example 3: - * - * - * Input: 4 - * Output: 3 - * Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. - * - * - * - * - * Note: - * - * 0 ≤ N ≤ 30. - * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/fibonacci-number/ -// discuss: https://leetcode.com/problems/fibonacci-number/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn fib(n: i32) -> i32 { - if n == 0 { - return 0; - } - let mut f = (0, 1); - for _ in 1..n { - f = (f.1, f.0 + f.1); - } - return f.1; - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_1013() { - assert_eq!(Solution::fib(2), 1); - assert_eq!(Solution::fib(3), 2); - assert_eq!(Solution::fib(4), 3); - } -} diff --git a/src/solution/s0704_binary_search.rs b/src/solution/s0704_binary_search.rs deleted file mode 100644 index 26ed0c8d..00000000 --- a/src/solution/s0704_binary_search.rs +++ /dev/null @@ -1,83 +0,0 @@ -/** - * [792] Binary Search - * - * Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. - * - *
- * Example 1: - * - * - * Input: nums = [-1,0,3,5,9,12], target = 9 - * Output: 4 - * Explanation: 9 exists in nums and its index is 4 - * - * - * - * Example 2: - * - * - * Input: nums = [-1,0,3,5,9,12], target = 2 - * Output: -1 - * Explanation: 2 does not exist in nums so return -1 - * - * - * - * - * Note: - * - *
    - * You may assume that all elements in nums are unique. - * n will be in the range [1, 10000]. - * The value of each element in nums will be in the range [-9999, 9999]. - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/binary-search/ -// discuss: https://leetcode.com/problems/binary-search/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here -use std::cmp::Ordering; - -impl Solution { - pub fn search(nums: Vec, target: i32) -> i32 { - let mut lo = 0i32; - let mut hi = (nums.len() as i32) - 1; - while lo <= hi { - let mid = lo + (hi - lo) / 2; - match nums[mid as usize].cmp(&target) { - Ordering::Less => { - lo = mid + 1; - } - Ordering::Greater => { - hi = mid - 1; - } - Ordering::Equal => { - return mid; - } - } - } - -1 - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_792() { - assert_eq!(Solution::search(vec![-1, 0, 3, 5, 9, 12], 9), 4); - assert_eq!(Solution::search(vec![-1, 0, 3, 5, 9, 12], 2), -1); - assert_eq!(Solution::search(vec![1], 1), 0); - assert_eq!(Solution::search(vec![5], -5), -1); - assert_eq!(Solution::search(vec![5], 6), -1); - assert_eq!(Solution::search(vec![1, 2], 0), -1); - assert_eq!(Solution::search(vec![1, 2], 1), 0); - assert_eq!(Solution::search(vec![1, 2], 2), 1); - assert_eq!(Solution::search(vec![1, 2], 3), -1); - } -} diff --git a/src/solution/s0969_pancake_sorting.rs b/src/solution/s0969_pancake_sorting.rs deleted file mode 100644 index 541ae423..00000000 --- a/src/solution/s0969_pancake_sorting.rs +++ /dev/null @@ -1,148 +0,0 @@ -/** - * [1009] Pancake Sorting - * - * Given an array A, we can perform a pancake flip: We choose some positive integer k <= A.length, then reverse the order of the first k elements of A. We want to perform zero or more pancake flips (doing them one after another in succession) to sort the array A. - * - * Return the k-values corresponding to a sequence of pancake flips that sort A. Any valid answer that sorts the array within 10 * A.length flips will be judged as correct. - * - * - * - * Example 1: - * - * - * Input: [3,2,4,1] - * Output: [4,2,4,3] - * Explanation: - * We perform 4 pancake flips, with k values 4, 2, 4, and 3. - * Starting state: A = [3, 2, 4, 1] - * After 1st flip (k=4): A = [1, 4, 2, 3] - * After 2nd flip (k=2): A = [4, 1, 2, 3] - * After 3rd flip (k=4): A = [3, 2, 1, 4] - * After 4th flip (k=3): A = [1, 2, 3, 4], which is sorted. - * - * - *
- * Example 2: - * - * - * Input: [1,2,3] - * Output: [] - * Explanation: The input is already sorted, so there is no need to flip anything. - * Note that other answers, such as [3, 3], would also be accepted. - * - * - * - *
- * - * Note: - * - *
    - * 1 <= A.length <= 100 - * A[i] is a permutation of [1, 2, ..., A.length] - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/pancake-sorting/ -// discuss: https://leetcode.com/problems/pancake-sorting/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn pancake_sort(a: Vec) -> Vec { - let len = a.len(); - if len <= 1 { - return Vec::new(); - } - let mut b = a.clone(); - let mut res: Vec = Vec::new(); - for i in 0..len { - if i == (len - 1) { - break; - } - let k = (len - i) as i32; - let index = Solution::find_k(&b, k); - if index == (k - 1) as usize { - continue; - } - if index != 0usize { - Solution::pancake_oper(&mut b, index, &mut res); - } - Solution::pancake_oper(&mut b, (k - 1) as usize, &mut res); - } - // println!("{:?}", b); - res - } - - fn find_k(a: &Vec, k: i32) -> usize { - for i in 0..(k - 1) { - if a[i as usize] == k { - return i as usize; - } - } - (k - 1) as usize - } - - pub fn pancake_oper(a: &mut Vec, index: usize, res: &mut Vec) { - let mut helper = Vec::new(); - for i in 0..(index + 1) { - helper.push(a[index - i]); - } - for i in 0..(index + 1) { - a[i] = helper[i]; - } - res.push((index + 1) as i32); - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - use rand::seq::SliceRandom; - use rand::{thread_rng, Rng}; - - #[test] - fn test_1009() { - for _i in 0..20 { - let mut rng = rand::thread_rng(); - let size = rng.gen_range(0, 1000); - let sorted_vector = make_sorted_vector(size); - let mut shuffled_vector = make_shuffled_vector(&sorted_vector); - let res = Solution::pancake_sort(shuffled_vector.clone()); - let oper_num = res.len(); - apply_pancake_sort_res(&mut shuffled_vector, res); - assert_eq!(shuffled_vector, sorted_vector); - assert!(oper_num < (size * 10) as usize); - } - } - - fn make_sorted_vector(i: i32) -> Vec { - (1..i + 1).collect() - } - - fn make_shuffled_vector(a: &Vec) -> Vec { - let mut rng = thread_rng(); - let mut res = a.clone(); - res.shuffle(&mut rng); - res - } - - fn apply_pancake_sort_res(shuffled_vecter: &mut Vec, oper: Vec) { - for i in oper { - pancake_oper(shuffled_vecter, (i - 1) as usize); - } - } - - pub fn pancake_oper(a: &mut Vec, index: usize) { - let mut helper = Vec::new(); - for i in 0..(index + 1) { - helper.push(a[index - i]); - } - for i in 0..(index + 1) { - a[i] = helper[i]; - } - } -} diff --git a/src/solution/s1018_binary_prefix_divisible_by_5.rs b/src/solution/s1018_binary_prefix_divisible_by_5.rs deleted file mode 100644 index b2bb1839..00000000 --- a/src/solution/s1018_binary_prefix_divisible_by_5.rs +++ /dev/null @@ -1,106 +0,0 @@ -/** - * [1071] Binary Prefix Divisible By 5 - * - * Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i] interpreted as a binary number (from most-significant-bit to least-significant-bit.) - * - * Return a list of booleans answer, where answer[i] is true if and only if N_i is divisible by 5. - * - * Example 1: - * - * - * Input: [0,1,1] - * Output: [true,false,false] - * Explanation: - * The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. Only the first number is divisible by 5, so answer[0] is true. - * - * - * Example 2: - * - * - * Input: [1,1,1] - * Output: [false,false,false] - * - * - * Example 3: - * - * - * Input: [0,1,1,1,1,1] - * Output: [true,false,false,false,true,false] - * - * - * Example 4: - * - * - * Input: [1,1,1,0,1] - * Output: [false,false,false,false,false] - * - * - * - * - * Note: - * - *
    - * 1 <= A.length <= 30000 - * A[i] is 0 or 1 - *
- * - */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/binary-prefix-divisible-by-5/ -// discuss: https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -impl Solution { - pub fn prefixes_div_by5(a: Vec) -> Vec { - let mut ret = vec![]; - let mut n = 0; - for i in a { - let remain = (n * 2 + i) % 5; - ret.push(remain == 0); - n = remain; - } - - ret - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_1071() { - assert_eq!( - Solution::prefixes_div_by5(vec![0, 1, 1]), - vec![true, false, false] - ); - assert_eq!( - Solution::prefixes_div_by5(vec![1, 1, 1]), - vec![false, false, false] - ); - assert_eq!( - Solution::prefixes_div_by5(vec![0, 1, 1, 1, 1, 1]), - vec![true, false, false, false, true, false] - ); - assert_eq!( - Solution::prefixes_div_by5(vec![1, 1, 1, 0, 1]), - vec![false, false, false, false, false] - ); - assert_eq!( - Solution::prefixes_div_by5(vec![ - 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, - 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1 - ]), - vec![ - false, false, false, false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, true, false, false, true, true, - true, true, false - ] - ); - } -} diff --git a/src/solution/s1046_last_stone_weight.rs b/src/solution/s1046_last_stone_weight.rs deleted file mode 100644 index 871b4eb4..00000000 --- a/src/solution/s1046_last_stone_weight.rs +++ /dev/null @@ -1,78 +0,0 @@ -/** - * [1127] Last Stone Weight - * - * We have a collection of rocks, each rock has a positive integer weight. - * - * Each turn, we choose the two heaviest rocks and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: - * - * - * If x == y, both stones are totally destroyed; - * If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. - * - * - * At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.) - * - * - * - * Example 1: - * - * - * Input: [2,7,4,1,8,1] - * Output: 1 - * Explanation: - * We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, - * we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, - * we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, - * we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone. - * - * - * - * Note: - * - *
    - * 1 <= stones.length <= 30 - * 1 <= stones[i] <= 1000 - *
- */ -pub struct Solution {} - -// problem: https://leetcode.com/problems/last-stone-weight/ -// discuss: https://leetcode.com/problems/last-stone-weight/discuss/?currentPage=1&orderBy=most_votes&query= - -// submission codes start here - -use std::collections::BinaryHeap; -impl Solution { - pub fn last_stone_weight(stones: Vec) -> i32 { - let mut heap = BinaryHeap::new(); - heap.extend(stones); - loop { - if let Some(rock1) = heap.pop() { - if let Some(rock2) = heap.pop() { - if rock1 > rock2 { - heap.push(rock1 - rock2); - } - } else { - return rock1; - } - } else { - return 0; - } - } - } -} - -// submission codes end - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_1127() { - assert_eq!(Solution::last_stone_weight(vec![2, 7, 4, 1, 8, 1]), 1); - assert_eq!(Solution::last_stone_weight(vec![2]), 2); - assert_eq!(Solution::last_stone_weight(vec![2, 2]), 0); - assert_eq!(Solution::last_stone_weight(vec![1, 2, 2]), 1); - } -}