1. 程式人生 > >LeetCode--------55. Jump Game(陣列中的數字跳躍)

LeetCode--------55. 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.

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

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

.

Subscribe to see which companies asked this question

1.能不能調到最後一個元素

public class Solution {
    public boolean canJump(int[] nums) {
     int jump=0;
     int maxLen=0;
     int n=nums.length;
     if(nums.length==1){return true;}
     for(int i=0;i<n;i++){
         if(maxLen>=i){
             maxLen=Math.max(maxLen,(i+nums[i]));
             
         }
     }
     return maxLen>=nums.length-1;
    }
}

2.最少需要多少步
public class Solution {
    public int jump(int[] A) {
        if (A == null || A.length == 0) {
            return -1;
        }
        int start = 0, end = 0, jumps = 0;
        while (end < A.length - 1) {
            jumps++;
            int farthest = end;
            for (int i = start; i <= end; i++) {
                if (A[i] + i > farthest) {
                    farthest = A[i] + i;
                }
            }
            start = end + 1;
            end = farthest;
        }
        if(end<A.length-1){return -1;}
        else{return jumps;}
    }
}