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;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值