45. 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.)
Note:
You can assume that you can always reach the last index.
解析
- 運用bfs的思想,更新每一層的start,end,判斷是否到達數組結尾,返回bfs的層數
- 也是一種貪心的思想,
// 45. Jump Game II
class Solution_45 {
public:
int jump(vector<int>& nums) {
int n = nums.size(), step = 0;
int start = 0, end = 0; //bfs每一層的開始結束位置 //每層結束更新
while (end<n-1) //end<n時,end=n-1就能夠結束了
{
step++;
int maxend = end + 1; //至少走一步
for (int i = start; i <= end;i++)
{
if (i+nums[i]>n)
{
return step;
}
maxend = max(i+nums[i],maxend); //取當前這步範圍內,下一步最遠的位置;這裏能夠記錄最遠的那一步位置,直接start跳到那裏去;
}
start = end + 1;
end = maxend;
}
return step;
}
int jump(int A[], int n) {
vector<int> vec(A,A+n);
return jump(vec);
}
};
public class Solution {
public int jump(int[] nums) {
/**
* 本題用貪心法求解,
* 貪心策略是在每一步可走步長內,走最大前進的步數
*/
if(nums.length <= 1){
return 0;
}
int index,max = 0;
int step = 0,i= 0;
while(i < nums.length){
//若是能直接一步走到最後,直接步數+1結束
if(i + nums[i] >= nums.length - 1){
step++;
break;
}
max = 0;//每次都要初始化
index = i+1;//記錄索引,最少前進1步
for(int j = i+1; j-i <= nums[i];j++){//搜索最大步長內行走最遠的那步
if(max < nums[j] + j-i){
max = nums[j] + j-i;//記錄最大值
index = j;//記錄最大值索引
}
}
i = index;//直接走到能走最遠的那步
step++;//步長+1
}
return step;
}
}
題目來源