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;
            }
        }
    };
  • 相关阅读:
    elasticsearch插件开发
    elasticsearch启动流程
    HBase结构
    Scala统计一个文件所有单词出现的次数
    es基础知识
    Linux中Swap与Memory内存简单介绍
    linux 常用命令
    巅峰对决之Swarm、Kubernetes、Mesos
    【JS】JS知识小结
    【HTTP】HTTP状态码详解
  • 原文地址:https://www.cnblogs.com/hrnn/p/13425341.html
Copyright © 2011-2022 走看看