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.

Note:

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

题意:数组中的元素表示从该点最大跨越的步数。要求给出能够达到最终节点的最小跨越次数。

解题思路:

用贪心的方法,设定一个count数组,count[i]表示第i个点能跳到的最远的距离。max_num表示当前全局跳的最远的距离。

当max_num大于末尾时,则更新count[n-1]的值。否则,更新count[max_num]的值。

最后返回count[n-1]。

源码:

class Solution {
public:
    int jump(vector<int>& nums) {
        int n = nums.size();
        if(n==1)    return 0;
        vector<int> count(n, INT_MAX-1);
        count[0] = 0;
        int max_num = 0;
        for(int i=0; i<n; i++){
            max_num = max(max_num, i+nums[i]);
            if(max_num <= n-1) 
                count[max_num] = min(count[i]+1, count[max_num]);
            else count[n-1] = min(count[i]+1,count[n-1]);
        }
        return count[n-1];
    }
};
发布了73 篇原创文章 · 获赞 11 · 访问量 9477

猜你喜欢

转载自blog.csdn.net/fanyuwgy/article/details/103887243