zoukankan      html  css  js  c++  java
  • 跳步游戏

    题目:

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

    分析:每跳一步记录下此步能跳的最远位置,若最远位置超过了数组长度,循环结束,否则继续跳步。

    代码如下:

    int jump(int A[], int n) {
            if(n<=1)return 0;
            int position = 0,step=0,i=0;
            while(i<n&&i<=position)
            {
                int tmp=position;
                while(i<=tmp)
                {
                    if(i+A[i]>position)position=i+A[i];
                    i++;
                }
                step++;
                if(position>=n-1) return step;
            }
            return -1;
        }

  • 相关阅读:
    pandas:数据分析
    NumPy(数组计算)
    量化投资与python
    量化投资与python
    vue-cli之脚手架
    pycharm与github的使用
    GIT命令
    关于pytest的命令行传参
    python脚本测试websocket接口协议
    python关于type()与生成器generator的用法
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3045631.html
Copyright © 2011-2022 走看看