【Leetcode】经典的Jump Game in JAVA
2017-05-03 20:35
369 查看
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实现】【024-Swap Nodes in Pairs(成对交换单链表的结点)】
- 【LeetCode-面试算法经典-Java实现】【094-Binary Tree Inorder Traversal(二叉树中序遍历)】
- [leetcode-45]Jump Game II(java)
- [LeetCode][Java] Jump Game II
- 【LeetCode-面试算法经典-Java实现】【117-Populating Next Right Pointers in Each Node(二叉树链接右指针II)】
- leetcode:Jump Game II 【Java】
- 【LeetCode-面试算法经典-Java实现】【153-Find Minimum in Rotated Sorted Array(找旋转数组中的最小数字)】
- Java for LeetCode 045 Jump Game II
- 【LeetCode-面试算法经典-Java实现】【106-Construct Binary Tree from Inorder and Postorder Traversal(构造二叉树II)】
- 【LeetCode-面试算法经典-Java实现】【033-Search in Rotated Sorted Array(在旋转数组中搜索)】
- LeetCode 第四十五题(Jump Game II)Java
- Jump Game leetcode java
- [LeetCode][Java] Jump Game II
- 【LeetCode-面试算法经典-Java实现】【105-Construct Binary Tree from Preorder and Inorder Traversal(构造二叉树)】
- Jump Game leetcode java
- leetcode解题之45. Jump Game II&55. Jump Game java (跳跃游戏)
- 【LeetCode-面试算法经典-Java实现】【215-Kth Largest Element in an Array(数组中第K大的数)】
- 【LeetCode-面试算法经典-Java实现】【151-Reverse Words in a String(反转字符串中的单词)】