LeetCode-Jump Game

来源:互联网 发布:卡尔维诺 知乎 编辑:程序博客网 时间:2024/06/11 23:45

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.

此题意思是以当前的元素值作为向前跳动的步数,证明能否跳到最后一个元素。此题是典型的动态分析题目,用局部最优来理解。定义一个当前能够到达的元素下标值 reach ,选取当前局部最优能够跳到的下标,当 reach >= 数组的长度 - 1 时说明跳到数组的最后一个元素上面了,反之不能。时间复杂度为O(n),空间复杂度为O(1)。

代码:



0 0
原创粉丝点击