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;
        }

  • 相关阅读:
    博客作业6
    博客作业5
    3137102127 林志坤(实验3)
    3137102127 林志坤(实验2)
    个人简介
    Bookstore项目测试缺陷报告
    自我介绍
    第6次博客园作业
    软件测试第6次作业
    《构建之法》心得体会
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3045631.html
Copyright © 2011-2022 走看看