Jump Game II
Difficulty:hard
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.)
Note:
You can assume that you can always reach the last index.
题目中所给的数组表示当前位置上所能向前跳跃的步数,求从第一个位置开始,最少需要多少步能到达末尾。
一开始就想着用递归来做,果然是超过要求的时间复杂度了,最后用贪婪算法的思想才做出来。做法就是在当前位置上,在可以跳跃的位置中,找到下一次跳跃能跳到的最远距离的位置进行跳跃,重复以上步骤,知道可以到达末尾。
//int jump(vector<int>& nums) {//递归方法
//
// if (nums.size() <=1)
// return 0;
//
// int result = nums.size()-1;
// if (nums[0] >= nums.size()-1)
// return 1;
//
// for (int i = 1; i <= nums[0]; i++){
// if (i + nums[i] > nums[0]){
// vector<int> *tmp = new vector<int>(nums);
// while (tmp->size() > nums.size() - i)
// tmp->erase(tmp->begin());
// int tmp_result = 0;
//
// result = (tmp_result = (jump(*tmp) + 1)) < result ? tmp_result : result;
// }
//
// }
//
// return result;
//}
int jump(vector<int>& nums) {
int result = 0;
if (nums.size() <= 1)//小于等于一个数的情况
return 0;
if (nums[0] >= nums.size() - 1)//一步就能到的情况
return 1;
int current = 0;
while (1){
int nextPoint = -1;
int nextGet = -1;
if (current + nums[current] >= nums.size()-1)//当前点的步数足够到达末尾
return result + 1;
for (int i = current + 1; i <= (current + nums[current] < nums.size() - 1 ? current + nums[current] : nums.size() - 1); i++){//寻找最远能达到的下一点
if (i + nums[i]>=nextGet){
nextGet = i + nums[i];
nextPoint = i;
}
}
current = nextPoint;
result++;
}
}