45. Jump Game II

来源:互联网 发布:c语言utf8转unicode 编辑:程序博客网 时间:2024/06/06 04:17

题目:

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


本题的思路是基于贪心算法,对于每一个(curStart,curEnd)区间都有一个最远距离 dist

每当我们到达一个最远距离的时候,更新(curStart,curEnd)即可

注意边界条件是nums.size()-1


class Solution {public:    int jump(vector<int>& nums) {        int step=0,curEnd=0,dist=0;        for(int i=0;i<nums.size()-1;i++){            dist=max(dist,nums[i]+i);            if(i==curEnd){                step++;                curEnd=dist;            }        }        return step;    }};




原创粉丝点击