Skip to content

Commit 27023e7

Browse files
committed
Added Jump Game II
1 parent a7252d9 commit 27023e7

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

Diff for: src/jump_game_ii.rs

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/// You are given a 0-indexed array of integers `nums` of length `n`. You are
2+
/// initially positioned at `nums[0]`.
3+
///
4+
/// Each element `nums[i]` represents the maximum length of a forward jump
5+
/// from index `i`. In other words, if you are at `nums[i]`, you can jump
6+
/// to any `nums[i+j]` where:
7+
///
8+
/// * `0 <= j <= nums[i]` and
9+
///
10+
/// * `i + j < n`
11+
///
12+
/// Return the minimum number of jumps to reach `nums[n-1]`. The test cases
13+
/// are generated such that you can reach `nums[n-1]`.
14+
struct Solution;
15+
16+
impl Solution {
17+
18+
pub fn jump(nums: Vec<i32>) -> i32 {
19+
let n = nums.len();
20+
let mut result = 0;
21+
22+
let mut end = 0;
23+
let mut farthest = 0;
24+
25+
for i in 0..n-1 {
26+
let max_from_here = i + nums[i] as usize;
27+
farthest = farthest.max(max_from_here);
28+
29+
if i == end {
30+
result += 1;
31+
end = farthest;
32+
}
33+
}
34+
35+
result
36+
}
37+
38+
}
39+
40+
#[cfg(test)]
41+
mod tests {
42+
use super::Solution;
43+
44+
#[test]
45+
fn example_1() {
46+
let nums = vec![2,3,1,1,4];
47+
let result = Solution::jump(nums);
48+
assert_eq!(result, 2);
49+
}
50+
51+
#[test]
52+
fn example_2() {
53+
let nums = vec![2,3,0,1,4];
54+
let result = Solution::jump(nums);
55+
assert_eq!(result, 2);
56+
}
57+
58+
}

Diff for: src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ pub mod range_sum_query_immutable; // 30
4343
pub mod search_insert_position; // 35
4444
pub mod valid_sudoku; // 36 ✓
4545

46+
pub mod jump_game_ii; // 45 ✓
47+
4648
pub mod rotate_image; // 48
4749

4850
pub mod jump_game; // 55 ✓

0 commit comments

Comments
 (0)