【Leetcode】经典的Jump Game in JAVA
2014-11-19 16:08
387 查看
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 =
A =
这道题的巧妙之处在于,每一个值可以跳“值”大小步数。所以我们的思路如下:
1.记录到现在为止能跳到最远的距离,记为max
2.每一个点能走的步数,记为step,且每往前面走一步,step--
3.判断到这个点后往后跳的步数是不是大于max,如果是就更新max,不是就继续往前走
这样的话我们可以看到:如果前面这个点是零,且这个时候step步数不够你迈过去,那么就会自动跳出返回false。但是如果可以一直这么走走到终点,那么返回true
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.
这道题的巧妙之处在于,每一个值可以跳“值”大小步数。所以我们的思路如下:
1.记录到现在为止能跳到最远的距离,记为max
2.每一个点能走的步数,记为step,且每往前面走一步,step--
3.判断到这个点后往后跳的步数是不是大于max,如果是就更新max,不是就继续往前走
这样的话我们可以看到:如果前面这个点是零,且这个时候step步数不够你迈过去,那么就会自动跳出返回false。但是如果可以一直这么走走到终点,那么返回true
package testAndfun; public class jumpGame { public static void main(String args[]){ int[] A = {3,0,0,0}; jumpGame jp = new jumpGame(); if(jp.canJump(A)) System.out.println("We win"); else System.out.println("we lose"); } public boolean canJump(int[] A) { int max = 0; int step = 1; if(A.length<=1) return true; if(A[0]==0&&A.length>1) return false; for(int i=0;i<A.length;i++){ step--; if(i+A[i]>max){ max = i+A[i]; step = A[i]; } if(step==0 && i<A.length-1) return false; } return true; } }
相关文章推荐
- 【Leetcode】经典的Jump Game in JAVA
- 【Leetcode】Jump Game in JAVA
- 【LeetCode-面试算法经典-Java实现】【025-Reverse Nodes in k-Group(单链表中k个结点一组进行反转)】
- 【LeetCode-面试算法经典-Java实现】【105-Construct Binary Tree from Preorder and Inorder Traversal(构造二叉树)】
- leetcode:Jump Game II 【Java】
- [LeetCode][Java] Jump Game II
- LeetCode(045) Jump Game II (Java)
- 【LeetCode-面试算法经典-Java实现】【151-Reverse Words in a String(反转字符串中的单词)】
- LeetCode 第四十五题(Jump Game II)Java
- 【LeetCode-面试算法经典-Java实现】【154-Find Minimum in Rotated Sorted Array II(找旋转数组中的最小数字II)】
- [LeetCode][Java] Jump Game II
- 【LeetCode-面试算法经典-Java实现】【116-Populating Next Right Pointers in Each Node(二叉树链接右指针)】
- 【LeetCode-面试算法经典-Java实现】【081-Search in Rotated Sorted Array II(搜索旋转的排序数组)】
- leetcode解题之45. Jump Game II&55. Jump Game java (跳跃游戏)
- Jump Game leetcode java
- 【LeetCode-面试算法经典-Java实现】【024-Swap Nodes in Pairs(成对交换单链表的结点)】
- 【LeetCode-面试算法经典-Java实现】【106-Construct Binary Tree from Inorder and Postorder Traversal(构造二叉树II)】
- Jump Game leetcode java
- [leetcode-45]Jump Game II(java)
- 【LeetCode-面试算法经典-Java实现】【153-Find Minimum in Rotated Sorted Array(找旋转数组中的最小数字)】