Jump Game II 解答

Question

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

Solution

This problem can be transformed into "Given step n, what is the largest distance that you can reach?"

Beside maintaining an array to record farest reachable position, we need also know how farest current jump can reach.

Example

 1 public class Solution {
 2     public int jump(int[] nums) {
 3         if (nums == null || nums.length < 1)
 4             return -1;
 5         int length = nums.length;
 6         // Three variables
 7         // maxReach: max reachable position for current index and previous indexes
 8         // maxJumpReach: max position that can be reachable by n jump steps
 9         // jump: jump steps
10         int maxReach = nums[0];
11         int maxJumpReach = 0;
12         int jump = 0;
13         for (int i = 0; i < length && maxJumpReach <= (length - 1); i++) {
14             if (i > maxJumpReach) {
15                 jump++;
16                 maxJumpReach = maxReach;
17             }
18             maxReach = Math.max(maxReach, i + nums[i]);
19         }
20         return jump;
21     }
22 }

 

posted @ 2015-10-08 00:44  树獭君  阅读(152)  评论(0编辑  收藏  举报