Skip to content

Fix the inconsistency #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,11 +186,11 @@ mod n0215_kth_largest_element_in_an_array;
mod n0216_combination_sum_iii;
mod n0217_contains_duplicate;
mod n0218_the_skyline_problem;
mod n0220_contains_duplicate_iii;
mod n0219_contains_duplicate_ii;
mod n0220_contains_duplicate_iii;
mod n0221_maximal_square;
mod n0223_rectangle_area;
mod n0222_count_complete_tree_nodes;
mod n0223_rectangle_area;
mod n0224_basic_calculator;
mod n0225_implement_stack_using_queues;
mod n0226_invert_binary_tree;
Expand Down Expand Up @@ -227,12 +227,14 @@ mod n0300_longest_increasing_subsequence;
mod n0301_remove_invalid_parentheses;
mod n0303_range_sum_query_immutable;
mod n0304_range_sum_query_2d_immutable;
mod n1009_pancake_sorting;
mod n0306_additive_number;
mod n0307_range_sum_query_mutable;
mod n0309_best_time_to_buy_and_sell_stock_with_cooldown;
mod n0310_minimum_height_trees;
mod n0312_burst_balloons;
mod n0313_super_ugly_number;
mod n1013_fibonacci_number;
mod n0792_binary_search;
mod n1009_pancake_sorting;
mod n1013_fibonacci_number;
mod n1071_binary_prefix_divisible_by_5;
mod n1127_last_stone_weight;
57 changes: 36 additions & 21 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,21 @@ mod problem;

use std::env;
use std::fs;
use std::path::{Path};
use std::io::Write;
use std::io;
use std::io::Write;
use std::path::Path;

/// main() helps to generate the submission template .rs
fn main() {
println!("Welcome to leetcode-rust system.");
let mut solved_ids = get_solved_ids();
loop {
println!("Please enter a problem id, or enter \"random\" to generate a random problem.");
println!("Please enter a frontend problem id, or \"random\" to generate a random one.");
let mut is_random = false;
let mut id :u32 = 0;
let mut id: u32 = 0;
let mut id_arg = String::new();
io::stdin().read_line(&mut id_arg)
io::stdin()
.read_line(&mut id_arg)
.expect("Failed to read line");
let id_arg = id_arg.trim();
match id_arg {
Expand All @@ -29,23 +30,30 @@ fn main() {
id = generate_random_id(&solved_ids);
is_random = true;
println!("Generate random problem: {}", &id);
},
}
_ => {
id = id_arg.parse::<u32>().expect(&format!("not a number: {}", id_arg));
id = id_arg
.parse::<u32>()
.expect(&format!("not a number: {}", id_arg));
if solved_ids.contains(&id) {
println!("The problem you chose is invalid (the problem may have been solved \
or may have no rust version).");
println!(
"The problem you chose is invalid (the problem may have been solved \
or may have no rust version)."
);
continue;
}
}
}

let problem = problem::get_problem(id)
.expect(&format!("Error: failed to get problem #{} \
(The problem may be paid-only or may not be exist).",
id));
let code = problem.code_definition.iter()
.filter(|&d| { d.value == "rust" })
let problem = problem::get_problem(id).expect(&format!(
"Error: failed to get problem #{} \
(The problem may be paid-only or may not be exist).",
id
));
let code = problem
.code_definition
.iter()
.filter(|&d| d.value == "rust")
.next();
if code.is_none() {
println!("Problem {} has no rust version.", &id);
Expand All @@ -54,7 +62,11 @@ fn main() {
}
let code = code.unwrap();

let file_name = format!("n{:04}_{}", problem.question_id, problem.title_slug.replace("-", "_"));
let file_name = format!(
"n{:04}_{}",
problem.question_id,
problem.title_slug.replace("-", "_")
);
let file_path = Path::new("./src").join(format!("{}.rs", file_name));
if file_path.exists() {
panic!("problem already initialized");
Expand Down Expand Up @@ -88,17 +100,20 @@ fn main() {
}
}

fn generate_random_id(except_ids : &Vec<u32>) -> u32 {
use std::fs;
fn generate_random_id(except_ids: &Vec<u32>) -> u32 {
use rand::Rng;
use std::fs;
let mut rng = rand::thread_rng();
loop {
let res :u32 = rng.gen_range(1, 1106);
let res: u32 = rng.gen_range(1, 1106);
if !except_ids.contains(&res) {
return res;
}
println!("Generate a random num ({}), but it is invalid (the problem may have been solved \
or may have no rust version). Regenerate..", res);
println!(
"Generate a random num ({}), but it is invalid (the problem may have been solved \
or may have no rust version). Regenerate..",
res
);
}
}

Expand Down
6 changes: 4 additions & 2 deletions src/n0001_two_sum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@ impl Solution {
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] },
None => {
map.insert(num, index);
}
Some(sub_index) => return vec![*sub_index as i32, index as i32],
}
}
vec![]
Expand Down
57 changes: 43 additions & 14 deletions src/n0002_add_two_numbers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
* 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:
*
*
Expand All @@ -17,31 +17,52 @@
*
*/
pub struct Solution {}
use super::util::linked_list::{ListNode, to_list};
use super::util::linked_list::{to_list, ListNode};

// submission codes start here

impl Solution {
pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
pub fn add_two_numbers(
l1: Option<Box<ListNode>>,
l2: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
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 },
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 }
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
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 };
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
}
Expand All @@ -50,17 +71,25 @@ impl Solution {

// 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![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![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]))
assert_eq!(
Solution::add_two_numbers(to_list(vec![0]), to_list(vec![0])),
to_list(vec![0])
)
}
}
16 changes: 12 additions & 4 deletions src/n0003_longest_substring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ impl Solution {
for idx in start..end {
if seq[end] == seq[idx] {
start = idx + 1;
break
break;
}
}
let curr = end - start + 1;
if curr > max { max = curr }
if curr > max {
max = curr
}
end += 1
}
max as i32
Expand All @@ -43,8 +45,14 @@ mod tests {

#[test]
fn test_3() {
assert_eq!(Solution::length_of_longest_substring("abcabcbb".to_string()), 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);
assert_eq!(
Solution::length_of_longest_substring("pwwkew".to_string()),
3
);
}
}
34 changes: 20 additions & 14 deletions src/n0004_median_of_two_sorted_arrays.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,29 @@
* [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 {}

Expand All @@ -47,7 +47,13 @@ mod tests {
#[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);
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
);
}
}
Loading