标签:
【题目】
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
.
【分析】
1.记录一个step,表示还能往后走几步
2.遍历数组(每次都step--),如果step小于0,则返回false(表示不可达);如果step<num[i],则更新step(step=num[i])
3.跳出for循环,说明可到达最后一个位置,返回true
【算法实现】
public class Solution { public boolean canJump(int[] nums) { int step=1; for(int i=0;i<nums.length;i++) { step--; if(step<0) return false; if(nums[i]>step) step=nums[i]; } return true; } }
标签:
原文地址:http://www.cnblogs.com/hwu2014/p/4444983.html