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.
Example:
Input: [2,3,1,1,4] Output: 2 Explanation: 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.
Note:
You can assume that you can always reach the last index.
思路:
贪心算法。只有在不得不跳的时候if(jump>max_index),才跳一步,选择下一次可达最远的地方跳,并把每次跳跃点的next_num[jump]记录在max_index中,因为是判断条件,所以不能随意更新,寻找路径中最大的next_num用next_max_index更新,并在每次跳跃时if(jump > max_index )才更新 max_index = next_max_index;。
第一次写出现了很多错误,需要再次思考几次,理清原因。
class Solution {
public int jump(int[] nums) {
int len = nums.length;
if(nums[0]<1 || len < 2) //如果数组长度小于2或者num[0]=0 ,返回0,因为要么不用跳跃,要么无法跳跃到后一个点
return 0;
int[] next_nums = new int[len];
for(int i=0; i<len; i++)
{
next_nums[i] = i+nums[i];
}
int jump = 0;
int max_index = next_nums[0];
int next_max_index =next_nums[0];
int jump_times = 0;
// while(jump < len && next_max_index < len )错误 [1,2,3] wrongout:1 correct answer:2
while(jump < len)
{
//if(jump == max_index ) 错误
if(jump > max_index )
{
jump_times++;
max_index = next_max_index;
}
if(next_max_index < next_nums[jump])
next_max_index = next_nums[jump];
jump++;
}
//错误的if Input: [5,9,3,2,1,0,2,3,3,1,0,0]
//Output: 0
//Expected: 3
//if(next_max_index < len)
// return 0; //到不了,返回0
// else
return ++jump_times;
}
}
博主学习笔记,转载请注明出处,谢谢~