55. 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
.
大意
答案
1 | class Solution { |
思路
设置一个reach,代表可以走到最远的距离,遍历数组,不断更新最远的距离,同时,假如有一个序列 32104,在第四个数卡住,所以reach至少要大于遍历的序号,走到最后时,reach是3,所以走不到第四个位置,就结束循环,能走到最后就返回true,否则返回false。因为最极端的情况就是全1走完(其中有一个0都不行),所以第i个数字,他的reach至少是i。也就是走完第一个数字,至少能到第二个数字,走完第二个,至少能到第三个数字…依次类推。
Author: corn1ng
Link: https://corn1ng.github.io/2017/11/14/算法/leetcode55/
License: 知识共享署名-非商业性使用 4.0 国际许可协议