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.

     Notice

    This problem have two method which is Greedy and Dynamic Programming.

    The time complexity of Greedy method is O(n).

    The time complexity of Dynamic Programming method is O(n^2).

    贪心思路:  用farthest 指针纪录 从开始节点(第0个元素)到当前节点能到达的最远距离;

                    初始值:  farthest = A[0]; 很显然,若A[0] = 0, farthest = 0, 在数组元素大于1的情况下,是不能跳到最后一个元素的。

                    通过一次遍历,算出结果。

                    贪心思路的原则是, 假定当前指针在第i个, 若farthest 能够跳到最后一个元素,直接结束。  

                    一次遍历的过程就是不停更新farthest与比较的过程 。

                    a[0] + 0 = farthest(0) 说明不能跳到最后一个元素 能否推出若 a[i] + i = farthest , 则不能跳到最后一个元素

                   

    public boolean canJump(int[] A) {
            // wirte your code here
           if(A == null || A.length <= 0) {
               return true;
           }
           
           int farthest = A[0];
           for(int i = 0 ; i < A.length - 2; i++) {
               if(A[i] + i > farthest ) {
                   farthest = A[i] + i;
               }
               
               if(farthest >= A.length - 1) {
                   return true;
               }
               
               if(farthest == i) {
                   return false;
               }
           }
           
           return farthest >= A.length - 1;
        }

              

                                    

                    

  • 相关阅读:
    微信小程序之阻止冒泡事件
    微信小程序之生成二维码
    微信小程序之数据缓存和数据获取
    微信小程序之分享功能
    抽丝剥茧——策略设计模式
    抽丝剥茧——单例设计模式
    抽丝剥茧——备忘录设计模式
    手把手教你Smarty缓存技术(转)
    二级域名session 共享方案(转)
    MySQL监控、性能分析——工具篇
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6761474.html
Copyright © 2011-2022 走看看