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

  • 相关阅读:
    双向(端)链表、栈、队列
    WPF 3D基础(1)
    静态查找
    栈和队列 迷宫求解
    异步编程Demo
    WPF 3D基础(2)
    串操作
    链栈和链队
    Linux恢复数据
    word文件修复窍门
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3045631.html
Copyright © 2011-2022 走看看