Jump Game II

来源:互联网 发布:知轩藏书进不去 编辑:程序博客网 时间:2024/06/06 05:10

思路就是首先走出第一步, 在最大步数中找出下一个的最大步数


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.)


class Solution {public:    int jump(int A[], int n) {    if (n==0 || n==1)    return 0;    int i=0, m=0,jmp=0;    while(i<n){    m=max(m,A[i]+i);    if (m>0)    jmp++;    if (m>=n-1)    return jmp;    int tmp=0;    for (int j=i+1; j<=m; j++){    if (A[j]+j>tmp){    tmp=A[j]+j;    i=j;    }    }    }    return jmp;    }};


0 0
原创粉丝点击