Skip to content

Commit dc4d833

Browse files
authored
Merge pull request #24 from jtr109/jump-game-ii
Jump game ii
2 parents 2f07492 + 67bdf86 commit dc4d833

File tree

4 files changed

+52
-0
lines changed

4 files changed

+52
-0
lines changed

Cargo.lock

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,5 @@ members = [
1616
"course_schedule_iii",
1717
"prefix_and_suffix_search",
1818
"non_decreasing_array",
19+
"jump_game_ii",
1920
]

jump_game_ii/Cargo.toml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
[package]
2+
name = "jump_game_ii"
3+
version = "0.1.0"
4+
authors = ["Ryan Li <conbas2019@gmail.com>"]
5+
edition = "2018"
6+
7+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8+
9+
[dependencies]

jump_game_ii/src/lib.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
pub struct Solution {}
2+
3+
impl Solution {
4+
pub fn jump(nums: Vec<i32>) -> i32 {
5+
let mut target = nums.len() - 1;
6+
let mut jumps = 0;
7+
'target_loop: loop {
8+
if target == 0 {
9+
break;
10+
}
11+
for cursor in 0..target {
12+
if cursor + nums[cursor] as usize >= target {
13+
jumps += 1;
14+
target = cursor;
15+
continue 'target_loop;
16+
}
17+
}
18+
}
19+
jumps
20+
}
21+
}
22+
23+
#[cfg(test)]
24+
mod test {
25+
use super::*;
26+
27+
#[test]
28+
fn example_1() {
29+
let nums = vec![2, 3, 1, 1, 4];
30+
assert_eq!(Solution::jump(nums), 2);
31+
}
32+
33+
#[test]
34+
fn example_2() {
35+
let nums = vec![2, 3, 0, 1, 4];
36+
assert_eq!(Solution::jump(nums), 2);
37+
}
38+
}

0 commit comments

Comments
 (0)