Jump Game I
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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
说是贪心算法,其实就是记录数组中每个元素可以移动的最大位置。之前思路不太清晰,写代码一定要有清晰的思路啊,而且想问题应该要从多个角度去想才对。
class Solution { public: bool canJump(vector<int>& nums) { int size=nums.size(); // int flag=0; if(size==1) return 1; int maxstep=nums[0]; for(int i=1;i<size;i++) { if(maxstep==0) return 0; maxstep--; maxstep=max(maxstep,nums[i]); } return 1; } };
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.
仍然使用贪心,只不过是要记录当前一跳所能到达的最远距离、上一跳所能达到的最远距离,和当前所使用跳数就可以了代码如下:
class Solution { public: int jump(vector<int>& nums) { int len=nums.size(); int cur=0; int last=0; int res=0; for(int i=0;i<len;i++) { if(i>cur) return -1; if(i>last) { last=cur; res++; } cur=max(cur,i+nums[i]); } return res; } };