Leetcode Jump Game II

来源:互联网 发布:笔记本安装linux 编辑:程序博客网 时间:2024/06/06 19:47

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

题意是用最少次的jump到达最后一个位置。

result记录当前跳跃的次数

maxstep记录每一次最远到达的最值

curstep记录当前可以到达的位置,在curstep小于 i 时就需要jump

一下代码属于参考

class Solution {public:    int jump(vector<int>& nums) {        int maxstep=0;        int curstep=0;        int result = 0;        for(int i=0; i<nums.size();i++)        {            if(curstep < i)            {                result++;                curstep = maxstep;            }            maxstep = max(maxstep,nums[i]+i);        }        return result;    }};


0 0
原创粉丝点击