Java for LeetCode 045 Jump Game II

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.)

解题思路:

题目不难,只需每次找出向右的最大范围的指针maxStepIndex即可,为了减少遍历,可以用一个指针start维护每次遍历的起始位置,JAVA实现如下:

static public int jump(int[] nums) {
int result=0,index=0,maxStepIndex=0,start=0;
if(nums.length>1&&0+nums[0]>=nums.length-1)
return 1;
while(index<nums.length-1){
result++;
for(int i=start;i<=index+nums[index];i++){
if(i+nums[i]>=nums.length-1)
return result+1;
if(i+nums[i]>=nums[maxStepIndex]+maxStepIndex)
maxStepIndex=i;
}
start=index+nums[index]+1;
index=maxStepIndex;
}
return 0;
}
上一篇:MAC下MySQL初始密码忘记修改初始密码


下一篇:cocos2dx实现经典飞机大战