Jump Game II(另类BFS)

来源:互联网 发布:ec6108v9不能安装软件 编辑:程序博客网 时间:2024/06/07 16:27

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

Note:
You can assume that you can always reach the last index.

class Solution {public:    int jump(vector<int>& nums) {        int l=0,r=0;        int maxr=-1;        int ans=0;        int n=nums.size();        while(1)        {            if(r>=n-1)                return ans;            for(int i=l;i<=r;i++)            {                maxr=max(maxr,nums[i]+i);            }             l=r+1;            r=maxr;            ans++;        }    }};
原创粉丝点击