zoukankan      html  css  js  c++  java
  • leetcode105: jump-game-ii

    题目描述

    给出一个非负整数数组,你最初在数组第一个元素的位置
    数组中的元素代表你在这个位置可以跳跃的最大长度
    你的目标是用最少的跳跃次数来到达数组的最后一个元素的位置
    例如

    给出数组 A =[2,3,1,1,4]

    最少需要两次才能跳跃到数组最后一个元素的位置。(从数组下标为0的位置跳长度1到达下标1的位置,然后跳长度3到数组最后一个元素的位置)

    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 is2. (Jump1step from index 0 to 1, then 3 steps to the last index.)


    示例1

    输入

    复制
    [2,3,1,1,4]

    输出

    复制
    2
    

    class Solution {
    public:
        /**
         *
         * @param A int整型一维数组
         * @param n int A数组长度
         * @return int整型
         */
        int jump(int* A, int n) {
            // write code here
            int curReach=0,maxReach=0,steps=0;
            for (int i=0;i<n && i<=maxReach;i++)
            {
                if (i>curReach)
                {
                    ++steps;
                    curReach=maxReach;
                }
                maxReach=max(maxReach,i+A[i]);
            }
            
            if (maxReach<n-1){
                return -1;
                
            }else {
                return steps;
            }
        }
    };
  • 相关阅读:
    软件架构实现
    UVa644
    如何理解Hibernate中的HibernateSessionFactory类
    在pcDuino上使用蓝牙耳机玩转音乐
    Java Web----Java Web的数据库操作(三)
    Pylons Controller里面Session.commit()总是出现rollback
    ORACLE的SQL JOIN方式小结
    关于数据库学习进阶的一点体悟
    IO is frozen on database xxx, No user action is required
    ORACLE等待事件:enq: TX
  • 原文地址:https://www.cnblogs.com/hrnn/p/13425341.html
Copyright © 2011-2022 走看看