leetcode 045 —— Jump Game II

来源:互联网 发布:四川网络大学 编辑:程序博客网 时间:2024/05/21 19:22

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


思路:贪心算法,记录之前  所能到达的最远距离last,现在所能到达的最远距离cur。


class Solution {public:int jump(vector<int>& nums) {int res(0);int last(0);    //之前记录的所能到达的最远,如果i小于这个数int cur(0);//for (int i = 0; i < nums.size() && i <= cur; i++){if (i>last){  //如果i已经前进到 超过了 之前所能达到的最远处,那个就可以更新last,并且跳跃数也能+1.last = cur;res++;}cur = max(cur, nums[i] + i);}return res;}};


0 0
原创粉丝点击