LeetCode Jump Game

本文提供LeetCode跳跃游戏问题的解决方案,使用Java实现。通过维护最大跳跃距离来判断是否能到达数组最后一个位置,提供了两种实现方式。

原题链接在这里:https://leetcode.com/problems/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.

题解:

维护一个当前能跳到的最大值maxJump, 若是maxJump 已经>=nums.length-1, 说明能跳到最后一个点,return true.

若是过程中maxJump <= i, 说明跳到当前点便不能往前,跳出loop, return false.

Time Complexity: O(n). Space: O(1).

AC Java:

 1 public class Solution {
 2     public boolean canJump(int[] nums) {
 3         if(nums == null || nums.length == 0){
 4             return false;
 5         }
 6         int maxJump = 0;
 7         for(int i = 0; i<nums.length; i++){
 8             maxJump = Math.max(maxJump,i+nums[i]);
 9             if(maxJump >= nums.length-1){
10                 return true;
11             }
12             if(maxJump <= i){
13                 break;
14             }
15         }
16         return false;
17     }
18 }

 下面的Method 2 更加模板化,方便于Jump Game II的操作。maxJump同样是需要维护的能跳到的最大值,每当 i 大于maxJump时就说明脱节了,

maxJump到不了i 不对maxJump做进一步更新。

loop后面检查maxJump 有没有到 最后一个元素,所示没到,就返回false, 到了就返回 true.

Time Complexity: O(n), Space O(1).

AC Java:

 1 public class Solution {
 2     public boolean canJump(int[] nums) {
 3         if(nums == null || nums.length == 0){
 4             return false;
 5         }
 6         int maxJump = 0;
 7         for(int i = 0; i<nums.length && i<=maxJump; i++){
 8             maxJump = Math.max(maxJump, i+ nums[i]);
 9         }
10         return maxJump<nums.length-1 ? false:true;
11     }
12 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4834075.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值