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.)
传统的BFS要个栈,但是如果你脑补一下BFS一层层扩展的过程的话,就发现每一层的所有节点其实在数组上都是连续的,用两个Index来标志这两层就好了嘛。
这样的好处就是不用额外的空间了。
下面[pre,farest]就是当前可以跳达的一层,然后whilie里的循环就是根据这一层得到下一层的新的farest区间。
题目没有说跳达不了的情况,这里一并处理了,跳不到会返回-1.
class Solution { public: int jump(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function assert(A&&n>=0); if ( n<=1 ) return 0; int pre=0,farest=A[0]; int curJump=1; while(pre<farest) { if ( farest>=n-1 ) return curJump; int t=farest; while(pre<=t) { farest=max(farest,A[pre]+pre); ++pre; } --pre; curJump++; } return -1; } };
Jump Game:
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(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function assert(A&&n>=1); int pre=0,far=A[0]; while(pre<=far) { if ( far>=n-1) return true; int tmp=far; while(pre<=tmp) { far=max(far,A[pre]+pre); pre++; } } return false; } };