Jump Game | & ||

Posted 北叶青藤

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jump Game | & ||相关的知识,希望对你有一定的参考价值。

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.

Example

A = [2,3,1,1,4], return true.

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

分析:

使用一个variable来保存当前剩余的“可跳的步数”,如果小于等于0,则表示不能再往下跳了。

 1 public class Solution {
 2     /**
 3      * @param A: A list of integers
 4      * @return: The boolean answer
 5      */
 6     public boolean canJump(int[] nums) {
 7         if (nums == null) return false;
 8         int stepsRemaining = 1;
 9         
10         for (int i = 0; i < nums.length; i++) {
11             stepsRemaining = Math.max(stepsRemaining - 1, nums[i]);
12             if (stepsRemaining <= 0 && i != nums.length - 1) return false;
13         }
14         return true;
15     }
16 }

Jump Game II

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.

Your goal is to reach the last index in the minimum number of jumps.

Example

Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

分析:

假定我们从 index i 处起跳, 那么最多能够跳到 i + A[i] (代码中的currentFarthestPoint)这么远。那么我们需要在 i 到 i + A[i] 这个范围内找到一个点 p,使得如果我们从那个p点开始跳,它能够比任何一个在i 到 A[i] 这些点都能reach更远或者相等的点(代码中的nextFarthestPoint),并把那个最远的点作为下一次跳能够到达的最远点。

 1 public class Solution {
 2     public int jump(int[] A) {
 3         if (A == null || A.length <= 1) return 0;
 4         int total = 0, currentFarthestPoint = A[0], i = 0;
 5         while (i < A.length) {
 6             int nextFarthestPoint = 0;
 7             while (i <= Math.min(A.length - 1, currentFarthestPoint)) {
 8                 nextFarthestPoint = Math.max(nextFarthestPoint, A[i] + i);
 9                 i++;
10             }
11             total++;
12             currentFarthestPoint = nextFarthestPoint;
13         }
14         return total;
15     }
16 }

 

以上是关于Jump Game | & ||的主要内容,如果未能解决你的问题,请参考以下文章

55. Jump Game I && II

jump-game

55.Jump Game

055. Jump Game

045. Jump Game II

LC 1340. Jump Game V