leetcode 45. Jump Game II贪心算法

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.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: 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.

题目链接:https://leetcode.com/problems/jump-game-ii/ 

这题我是在Leetcode 55题 Jump Game的基础上,利用贪心算法,在每一次找到中间目的地des时,i从0开始寻找局部最优解,利用cnt计数

class Solution {
public:
    int jump(vector<int>& nums) {
       int len=nums.size();
        if(len==1)
            return 0;
        int des=len-1;
        int i=0,cnt=0,flag=1;
        while(flag)
        {
            for(i=0;i<des&&flag;)
            {
                if(i+nums[i]>=des)
                {
                    des=i;
                    cnt++;
                    if(i==0)
                        flag=0;
                    i=0;
                }
                else
                {
                    i++;
                }
            }
        }    
        return cnt;
    }
};

就是时间有点长hhh

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/86526642