[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], return true.

A = [3,2,1,0,4], return false.

现给定一非负数组,初始位置为数组的首位。每一个数组中的元素表示你能从当前位置跳跃的最大步数,问:你能否跳到数组末尾?

解题思路

错误想法(最开始的想法):
   一直以贪心策略从初始位置开始跳跃最大步数从0跳到A[0]位置,在从A[0]跳到A[0]+A[A[0]]看最终能否到达数组尾部,如果到达不了,则跳跃最大步数-1,依次类推,使用递归来实现。

简单可行的思路:
   问题可以简单描述为,从0开始最远能走到哪?只要最大步数>=A.length - 1,就可以走到队尾。

代码

public static boolean canJump(int[] A) {
		int len = A.length;
		int maxStep = 0;

		if(len==0)
			return false;
		
		for (int i = 0; i < len - 1; i++) {
			if(maxStep >= i && i + A[i] > maxStep){
				maxStep = i + A[i];
			}
		}

		if(maxStep >= len - 1){
			return true;
		}
		return false;
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值