本文主要是介绍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.
For example:
A =[2,3,1,1,4], returntrue.
A =[3,2,1,0,4], returnfalse.
题意:
给定一个非负整数数组,初始位置是数组的第一个索引。数组中的每个元素表示该位置的最大跳转长度。确定是否能够达到最后一个索引。
从起点开始跳,它的当前数值表示它最大能走多少步,并不是一定要走这么多步,就拿第一个来说,2 后面是3,表示最多走3步,但是我走1步到1,再走1步都第四位,最后走一步也能到达终点4。这也是可以的。
解题思路:
理解题意就比较简单了,这里我们只管是否能达到终点,并不用理会走到这步的时候还剩下多少,所以这里可以使用贪心算法来解决。
我们用maxJump变量来维护最远走的距离,然后通过遍历数组,通过判断当前index是否已经大于maxJump 或者 i 已经到达终点,是就跳出循环,不然就不断的更新maxJump 的数值 ,最后判断 maxJump是否已经达到终点就行。
Java代码:
public boolean canJump(int[] A) {if(A == null || A.length == 0) {return false;}int n = A.length;int maxJump = 0;for(int i = 0; i < n;i++) {if(i > maxJump || i > n - 1) {break;}maxJump = Math.max(maxJump,i+A[i]);}return maxJump >= n-1;}
这篇关于LeetCode - jump-game的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!