leetcode(45):Jump Game II

来源:互联网 发布:jquery查询前清空数据 编辑:程序博客网 时间:2024/05/16 12:12

原题:
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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
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, then 3 steps to the last index.)

分析:此题是Jump Game的升级,需要求出从数组第一个元素到达最后一个元素的所需的最小的步数。
Java实现:时间复杂度为O(n)

public class Solution {    public int jump(int[] nums) {        int ret=0;//记录当前为止的步数        int last = 0;//记录上一跳能到达的最远距离,用数组下标表示        int cur = 0;//记录当前一跳能到达的最远距离        for (int i = 0; i < nums.length; i++) {            if(i>cur) {//当前一条不能到达,即最后一个元素不可达,返回-1                return -1;            }            if(i>last){//上一跳还不能到达当前位置,需要再跳一次,ret+1,并更新last值                ret++;                last=cur;            }            cur =Math.max(cur, i+nums[i]);//更新当前跳数        }        return ret;    }}
0 0
原创粉丝点击