Jump Game--lintcode

来源:互联网 发布:php源码测试软件 编辑:程序博客网 时间:2024/06/16 12:05

Description

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.

Example

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

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

我的思路:贪心算法。我开始的时候 是用i+=A[i],可是万一跳到数组中值为0的位置,就需要另外判断。是返回false,还是跳的步数少一点。很麻烦。都用到两个for循环了。网上搜索了一下。

参考网址:http://blog.csdn.net/linhuanmars/article/details/21354751

public boolean canJump(int[] A) {      if(A==null || A.length==0)          return false;      int reach = 0;      for(int i=0;i<=reach&&i<A.length;i++)      {          reach = Math.max(A[i]+i,reach);      }      if(reach<A.length-1)          return false;      return true;  }  

这里 i是一个一个加的,不是跳着的。
以2,3,1,1,4为例:
i=0 reach=max(0+2,0)=2;
i=1 reach=max(1+3,2)=4;
i=2 reach=max(2+1,4)=4;
i=3 reach=max(3+1,4)=4;
i=4 reach=max(4+4,4)=8.
返回true.
以3,2,1,0,4为例:
i=0, reach=max(0+3,0)=3;
i=1 reach=max(1+2,3)=3;
i=2 reach=max(2+1,3)=3;
i=3 reach=max(3+0,3)=3.
此时i<=reach。所以跳出for循环。而reach

原创粉丝点击