LeetCode--------55. Jump Game(数组中的数字跳跃)

来源:互联网 发布:2018java的就业前景 编辑:程序博客网 时间:2024/05/03 05:05

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;}    }}


0 0