From 923502c275d71b4a2a4de6d148f3a3d7e439f1e0 Mon Sep 17 00:00:00 2001 From: Luca Lombardo Date: Mon, 13 Nov 2023 23:23:27 +0100 Subject: [PATCH] new problem --- 2023_11_09/minimum-number-of-jumps/Cargo.toml | 8 ++++ 2023_11_09/minimum-number-of-jumps/README.md | 3 ++ .../minimum-number-of-jumps/src/main.rs | 44 +++++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 2023_11_09/minimum-number-of-jumps/Cargo.toml create mode 100644 2023_11_09/minimum-number-of-jumps/README.md create mode 100644 2023_11_09/minimum-number-of-jumps/src/main.rs diff --git a/2023_11_09/minimum-number-of-jumps/Cargo.toml b/2023_11_09/minimum-number-of-jumps/Cargo.toml new file mode 100644 index 0000000..b425262 --- /dev/null +++ b/2023_11_09/minimum-number-of-jumps/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "minimum-number-of-jumps" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/2023_11_09/minimum-number-of-jumps/README.md b/2023_11_09/minimum-number-of-jumps/README.md new file mode 100644 index 0000000..d99dddd --- /dev/null +++ b/2023_11_09/minimum-number-of-jumps/README.md @@ -0,0 +1,3 @@ +The algorithm iterates over the `nums` vector exactly once. For each element in the `nums` vector, it performs a constant amount of work - it updates `cur_farthest` and checks if `i` is equal to `cur_end`. If `i` is equal to `cur_end`, it increments `jumps` and updates `cur_end`. All of these operations take constant time. + +Therefore, the time complexity of the algorithm is O(n), where n is the length of the `nums` vector. diff --git a/2023_11_09/minimum-number-of-jumps/src/main.rs b/2023_11_09/minimum-number-of-jumps/src/main.rs new file mode 100644 index 0000000..63ea440 --- /dev/null +++ b/2023_11_09/minimum-number-of-jumps/src/main.rs @@ -0,0 +1,44 @@ +impl Solution { + pub fn jump(nums: Vec) -> i32 { + let mut jumps = 0; + let mut cur_end = 0; + let mut cur_farthest = 0; + for i in 0..nums.len() - 1 { + cur_farthest = cur_farthest.max(i + nums[i] as usize); + if i == cur_end { + jumps += 1; + cur_end = cur_farthest; + } + } + jumps + } +} + +struct Solution; + +// write tests + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1() { + assert_eq!(Solution::jump(vec![2, 3, 1, 1, 4]), 2); + } + + #[test] + fn test_2() { + assert_eq!(Solution::jump(vec![2, 3, 0, 1, 4]), 2); + } + + #[test] + fn test_3() { + assert_eq!(Solution::jump(vec![1, 2, 3]), 2); + } + + #[test] + fn test_4() { + assert_eq!(Solution::jump(vec![1, 2, 1, 1, 1]), 3); + } +}