1. Runtime Distribution
2. Submission Details
3. Description
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.
4. 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.)
5. Explanation
The main idea is based on greedy. Let's say the range of the current jump is [i, curEnd], curFarthest is the farthest point that all points in [i, curEnd] can reach. Once the current point reaches curEnd, then trigger another jump, and set the new curEnd with curFarthest, then keep the above steps
6. Code
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="C Greey" active="active"]
#define MAX(a,b) (((a)>(b))?(a):(b)) int jump(int* nums, int numsSize) { int curFurthest = 0, curEnd = 0, jump = 0; for (int i = 0; i= numsSize - 1) { jump++; break; } if (i == curEnd) { jump++; curEnd = curFurthest; } } return jump; }
[/restab]
[restab title="C DP"]
int jump(int* nums, int numsSize) { int* dp = malloc(sizeof(int) * numsSize); for(int i = 1; i< numsSize; i++) { dp[i] = numsSize + 1; } dp[0] = 0; for (int i = 0; i< numsSize; i++) { if (dp[i] < 0) continue; for(int j = 1; j <= nums[i] && i + j < numsSize; j++) { if (i + j < numsSize - 1 && nums[i] - j >= nums[i + j]) { dp[i + j] = -1; } else if(dp[i + j] > dp[i] + 1) { dp[i + j] = dp[i] + 1; } } } return dp[numsSize - 1]; }
[/restab]
[/restabs]
7.Test
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="C Greey" active="active"]
#include#include #define MAX(a,b) (((a)>(b))?(a):(b)) int jump(int* nums, int numsSize) { int curFurthest = 0, curEnd = 0, jump = 0; for (int i = 0; i = numsSize - 1) { jump++; break; } if (i == curEnd) { jump++; curEnd = curFurthest; } } return jump; } int main() { int nums[] = { 2,3,1,1,4 }; printf("%d\n", jump1(nums, 5)); system("pause"); return 0; }
[/restab]
[restab title="C DP"]
#include#include int jump(int* nums, int numsSize) { int* dp = malloc(sizeof(int) * numsSize); for(int i = 1; i< numsSize; i++) { dp[i] = numsSize + 1; } dp[0] = 0; for (int i = 0; i< numsSize; i++) { if (dp[i] < 0) continue; for(int j = 1; j <= nums[i] && i + j < numsSize; j++) { if (i + j < numsSize - 1 && nums[i] - j >= nums[i + j]) { dp[i + j] = -1; } else if(dp[i + j] > dp[i] + 1) { dp[i + j] = dp[i] + 1; } } } return dp[numsSize - 1]; } int main() { int nums[] = { 2,3,1,1,4 }; printf("%d\n", jump(nums, 5)); system("pause"); return 0; }
[/restab]
[/restabs]
Comments | NOTHING