zoukankan      html  css  js  c++  java
  • 45. Jump Game II (Array; Two-Pointers,Greedy)

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

    思路:此处不能用Greedy I的贪心算法,因为局部的最少跳数(到i位置的最少跳数),并不适用于全局(并不是从i往后跳也是最少跳数)。这里我们要检查所有上一个step能到的位置,即startPos与endPos之间的所有位置,而不是仅仅看最远的那个位置。在求endPos的时候,我们还是用了贪心法,即当前step能到达的最远位置。

    class Solution {
    public:
        int jump(vector<int>& nums) {
            int size = nums.size();
            int endPos = 0;
            int newEndPos = 0;
            int startPos = 0;
            int step = -1;
            
            while(startPos<size){
                for(int i = startPos; i <= endPos && i<size-1; i++){ //如果已经到了size-1位置(终点位置),那么不需要再计算了
                    newEndPos = max(newEndPos, i+nums[i]);
                }
                startPos = endPos+1;
                endPos = newEndPos;
                newEndPos = 0;
                step++;
            }
           
            return step;
        }
    };
  • 相关阅读:
    (33)ElasticSearch文档的核心元数据解析
    (32)ElasticSearch的容错机制
    (31)ElasticSearch水平扩容的过程
    (30)ElasticSearch两个节点环境中创建index解析
    (29)ElasticSearch分片和副本机制以及单节点环境中创建index解析
    UVA
    HDU
    ZOJ
    BZOJ1499: 瑰丽华尔兹(单调队列)
    UVALive
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4878928.html
Copyright © 2011-2022 走看看