Skip to content

Commit a7252d9

Browse files
committed
Added Jump Game
1 parent e3fb1f1 commit a7252d9

File tree

2 files changed

+55
-2
lines changed

2 files changed

+55
-2
lines changed

src/jump_game.rs

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/// You are given an integer array `nums`. You are initially positioned at the
2+
/// array's first index, and each element in the array represents your maximum
3+
/// jump length at that position.
4+
///
5+
/// Return `true` if you can reach the last index, or `false` otherwise.
6+
struct Solution;
7+
8+
impl Solution {
9+
10+
pub fn can_jump(nums: Vec<i32>) -> bool {
11+
let mut result = false;
12+
let mut max_so_far = 0;
13+
let n = nums.len();
14+
15+
for i in 0..n {
16+
if i > max_so_far {
17+
result = false;
18+
break;
19+
}
20+
let max_from_here = i + nums[i] as usize;
21+
max_so_far = max_so_far.max(max_from_here);
22+
if max_so_far >= n-1 {
23+
result = true;
24+
break;
25+
}
26+
}
27+
28+
result
29+
}
30+
31+
}
32+
33+
#[cfg(test)]
34+
mod tests {
35+
use super::Solution;
36+
37+
#[test]
38+
fn example_1() {
39+
let nums = vec![2,3,1,1,4];
40+
let result = Solution::can_jump(nums);
41+
assert!(result);
42+
}
43+
44+
#[test]
45+
fn example_2() {
46+
let nums = vec![3,2,1,0,4];
47+
let result = Solution::can_jump(nums);
48+
assert!(!result);
49+
}
50+
51+
}

src/lib.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ pub mod add_two_numbers; // 2
1919
pub mod length_of_longest_substring; // 3 ✓
2020
pub mod median_of_two_sorted_arrays; // 4
2121
pub mod longest_palindromic_substring; // 5
22-
pub mod zigzag_conversion; // 6
22+
pub mod zigzag_conversion; // 6
2323
pub mod reverse_integer; // 7 ✓
2424
pub mod string_to_integer; // 8 ✓
2525
pub mod palindrome_number; // 9 ✓
@@ -41,10 +41,12 @@ pub mod find_the_index_of_the_first_occurrence_in_a_string; // 28
4141
pub mod range_sum_query_immutable; // 30
4242

4343
pub mod search_insert_position; // 35
44-
pub mod valid_sudoku; // 36
44+
pub mod valid_sudoku; // 36
4545

4646
pub mod rotate_image; // 48
4747

48+
pub mod jump_game; // 55 ✓
49+
4850
pub mod length_of_last_word; // 58
4951

5052
pub mod plus_one; // 66

0 commit comments

Comments
 (0)