Jump Game (middle)
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
.
思路:开始没反应过来,从后往前记录能否到达 结果超时了
后来反应过来了 从前向后 记录能够到达的最大位置 最大位置>= n-1 就行了
bool canJump(int A[], int n) { int maxdis = 0; for(int i = 0; i < n ; i++) { if(maxdis < i) break; //如果当前最大位置都到不了i说明改格无法到达 maxdis = (i + A[i] > maxdis) ? i + A[i] : maxdis; } return maxdis >= n - 1; }
简化后代码
bool canJump(int A[], int n) { int maxdis = 0; for(int i = 0; i < n && maxdis >= i; i++) { maxdis = (i + A[i] > maxdis) ? i + A[i] : maxdis; } return maxdis >= n - 1; }
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.)
思路:我用动态规划做 O(n2)超时了
//超时 int jump(int A[], int n) { int * dp = (int *)malloc(n * sizeof(int)); dp[n - 1] = 0; for(int i = n - 2; i >= 0; i--) { dp[i] = n; for(int j = i + 1; j <= i + A[i] && j < n; j++) { dp[i] = (dp[i] < dp[j] + 1) ? dp[i] : dp[j] + 1; } } return dp[0]; }
下面贴上大神们的代码和思路,还没看
int jump(int A[], int n) { if(n == 0){ return 0; } int maxReachPos = A[0]; int curMaxReachPos = A[0]; int curStep = 1; for(int i = 1; i <= min(n, maxReachPos); i++){ curMaxReachPos = max(curMaxReachPos, i + A[i]); if(i == n - 1){ return curStep; } if(i == maxReachPos){ maxReachPos = curMaxReachPos; curStep++; } } return 0; }
The variable maxReachPos indicates the farthest reachable position and the variable curMaxReachPos indicates the current farthest reachable position.
At the very beginning, both maxReachPos and curMaxReachPos are equal to A[0].
In the For loop, we keep updating curMaxReachPos while i <= maxReachPos. However, if( i == n - 1), we return curStep, which is the minimum step. If i reaches the maxReachPos, we update maxReachPos with curMaxReachPos and increment curStep by one.
Finally, if we can't reach the end point, just return 0.
BFS做法
I try to change this problem to a BFS problem, where nodes in level i are all the nodes that can be reached in i-1th jump. for example. 2 3 1 1 4 , is 2|| 3 1|| 1 4 ||
clearly, the minimum jump of 4 is 2 since 4 is in level 3. my ac code.
int jump(int A[], int n) { if(n<2)return 0; int level=0,currentMax=0,i=0,nextMax=0; while(currentMax-i+1>0){ //nodes count of current level>0 level++; for(;i<=currentMax;i++){ //traverse current level , and update the max reach of next level nextMax=max(nextMax,A[i]+i); if(nextMax>=n-1)return level; // if last element is in level+1, then the min jump=level } currentMax=nextMax; } return 0; }