|
| 1 | +// 45. Jump Game II |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/jump-game-ii/ |
| 5 | +// |
| 6 | +// Tags: Array - Dynamic Programming - Greedy |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + // Visit each element of the array but do it in groups, we can see it as |
| 11 | + // treating each group as a level and the algorithm as BFS. For each |
| 12 | + // level, keep track of the farthest position we could jump to from this |
| 13 | + // level. When we get to the end of the level, add one to the number of |
| 14 | + // jumps that we have taken, and update the current level by updating the |
| 15 | + // last element we can explore to match the farthest element we can |
| 16 | + // reach from this level. |
| 17 | + // The algorithm repeatedly calculates the farthest point we can reach |
| 18 | + // from any of the positions that we can reach given the current number |
| 19 | + // of jumps, then "jump" once more and continue calculating. Each element |
| 20 | + // is only explored once. |
| 21 | + // |
| 22 | + // Time complexity: O(n) - Each element is visited once. |
| 23 | + // Space complexity: O(1) - Constant space. |
| 24 | + // |
| 25 | + // Runtime 2 ms Beats 80% |
| 26 | + // Memory 2.1 MB Beats 71.3% |
| 27 | + pub fn jump(nums: Vec<i32>) -> i32 { |
| 28 | + let n = nums.len(); |
| 29 | + let mut jumps = 0; |
| 30 | + let mut reach = 0; |
| 31 | + let mut next_reach = 0; |
| 32 | + for i in 0..n - 1 { |
| 33 | + let current_jump = i + nums[i] as usize; |
| 34 | + if current_jump > next_reach { |
| 35 | + next_reach = current_jump; |
| 36 | + } |
| 37 | + if next_reach >= n - 1 { |
| 38 | + return 1 + jumps as i32; |
| 39 | + } |
| 40 | + if i == reach { |
| 41 | + jumps += 1; |
| 42 | + reach = next_reach; |
| 43 | + } |
| 44 | + } |
| 45 | + jumps as i32 |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +// Tests. |
| 50 | +fn main() { |
| 51 | + assert_eq!(Solution::jump(vec![0]), 0); |
| 52 | + assert_eq!(Solution::jump(vec![2, 3, 1, 1, 4]), 2); |
| 53 | + assert_eq!(Solution::jump(vec![2, 3, 0, 1, 4]), 2); |
| 54 | + assert_eq!(Solution::jump(vec![2, 3, 0, 1, 4, 0, 0, 0, 2, 8, 7, 3]), 5); |
| 55 | + println!("All tests passed!") |
| 56 | +} |
0 commit comments