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

  • 相关阅读:
    线程唤醒
    以前、现在
    黑马程序员训练营基础测试
    流程图
    线程同步
    Thread联系
    Java线程
    Java中文件流笔记
    字符串习题
    匿名内部类
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3045631.html
Copyright © 2011-2022 走看看