Problem Description:
Given an array of non-negative integers, you is initially positioned at the first index of the array.
Each element of the array represents your maximum jump length is at that position.
Your goal is to reach the last index in the minimum number of jumps.
Examples:
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 and then steps to the last 3 index.)
Solution 1:
Public classSolution {/** * @parama:a List of lists of integers *@return: An integer*/ Private int[] steps; Public intJumpint[] A) {//Write your code here if(A = =NULL|| A.length = = 0) { return-1; } Steps=New int[A.length]; steps[0] = 0; for(inti = 1; i < a.length; i++) {Steps[i]=Integer.max_value; for(intj = 0; J < I; J + +) { if(Steps[j]! = Integer.max_value && (j + a[j]) >=i) {steps[i]= Steps[j] + 1; Break; } } } returnSteps[a.length-1]; }}View Code
This version was easy to understand. The time complexity of this algorithm is O (n*n).
Solution 2:
Public classSolution {/** * @parama:a List of lists of integers *@return: An integer*/ Public intJumpint[] A) {//Write your code here if(A = =NULL|| A.length = = 0) { return-1; } intStart = 0; intEnd = 0; intJumps = 0; while(End < A.length-1) {jumps++; intFarthest =end; for(inti = start; I <= end; i++) { if((i + a[i]) >farthest) {Farthest= i +A[i]; }} Start= end + 1; End=farthest; } returnjumps; }}View Code
This is the greedy version solution, we maintain-pointers start and end, first initialize start and end to 0, which me Ans We are at the index 0 and then when end < A.length-1, every time we jump, jumps++, we'll choose to the far Thest we can jump from whatever index between start and end to make sure we'll get the minimum jumps, so this is a greed Y algorithm.
Lintcode:jump Game II