码迷,mamicode.com
首页 > 其他好文 > 详细

Jump Game | & ||

时间:2016-07-05 06:24:18      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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.)

分析:

当我们在第一个点“2”的时候,我们需要遍历所有能够到达的点, i.e., 3, 1,然后找出当我们到达第3个点的时候,从哪个点(3或者1)起跳剩余跳数最多。

 1 public class Solution {
 2     /**
 3      * @param A: A list of lists of integers
 4      * @return: An integer
 5      */
 6     public int jump(int[] A) {
 7         if (A == null || A.length == 0) return 0;
 8 
 9         int position = 0, totalJumps = 0;
10         int remainingJumps = 0;
11         int jumps = A[0] + 1; // assume we jumps in the array at the beginning
12 
13         while (position < A.length) {
14             totalJumps++;
15             // find max remaining jumps in the "jump range"
16             for (int i = 1; i <= jumps; i++) {
17                 remainingJumps = Math.max(A[position], remainingJumps - 1);
18                 position++;
19                 if (position >= A.length) break;
20             }
21             jumps = remainingJumps;
22         }
23         return totalJumps;
24     } 
25 }

参考请注明出处:cnblogs.com/beiyeqingteng/

Jump Game | & ||

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5642208.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!