zoukankan      html  css  js  c++  java
  • [LeetCode] Jump Game

    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. 

    Determine if you are able to reach the last index.

    For example: A = [2,3,1,1,4], return true.

    A = [3,2,1,0,4], return false.

    这个题要小心各种陷阱,一不小心就会死循环什么的。

    class Solution {
    public:
        bool canJump(int A[], int n) {
            if(n<=1)
              return true;//输入[0]输出true
            int Index = A[0];
            while(Index<n-1){
               if(A[Index]!=0)
                 Index += A[Index];
               else{
                   int Index0 = Index;
                   for(int i = Index0-1;i>=0;i--){//遇到不前进的,往前回退一步,因为能到i,经过前面的步骤也能到i-1;
                       Index = i + A[i];
                       if(Index>Index0)
                           break;
                       else
                           continue;
                   
                   }//end for
                   
                   if(Index<=Index0)//经过处理后依然跨不过坎
                       return false;
               }//end if      
            }//end while
            if(Index>=n-1)
                return true;
            else
                return false;
        }
    };
  • 相关阅读:
    ES6标准入门之正则表达式的拓展
    将博客搬至CSDN
    CUDA杂谈
    QT源码解析笔记
    图解DTS和PTS
    图解 I帧,B帧以及P帧
    这半年的一些事情
    C++的一些编程规范
    pjsip与QT进行适配
    编程规范检测脚本
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3906571.html
Copyright © 2011-2022 走看看