算法系列——Jump Game

来源:互联网 发布:java接收json对象数组 编辑:程序博客网 时间:2024/06/06 02:43

题目描述

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.

解题思路

贪心算法,我们应该维护一个局部最优值和全局最优解决。

对于数组 [2,3,1,1,4]

索引 i 可跳跃值nums[i] 当前位置出发可以到达的最大距离 全局可达最大距离 0 2 2 2 1 3 4 4(可达) 2 1 3 4(可达) 3 1 4 4(可达) 4 4 8 8(可达)

最终结果是true.

对于数组[3,2,1,0,4]

索引 i 可跳跃值nums[i] 当前位置出发可以到达的最大距离 全局可达最大距离 0 3 3 3 1 2 3 3 2 1 3 3 3 0 3 3 4 4 8 8(不可达)

从表格中可以看到,在索引为3的位置,当前可达最大距离也就只能到这里,当索引为4时,返现4 大于最大可达距离,直接返回false.

程序实现

public class Solution {    public boolean canJump(int[] nums) {        int maxReach=0;        for( int i=0;i<nums.length;i++){            //如果当前索引超出能够到达的最大位置            if(i>maxReach)                break;            maxReach=Math.max(nums[i]+i,maxReach);            if(maxReach>=(nums.length-1))                return true;        }        return false;    }}
原创粉丝点击