new problem

main
Luca Lombardo 12 months ago
parent de0b29db31
commit 923502c275

@ -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]

@ -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.

@ -0,0 +1,44 @@
impl Solution {
pub fn jump(nums: Vec<i32>) -> 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);
}
}
Loading…
Cancel
Save