LeetCode 45. Jump Game II(跳格子)

来源:互联网 发布:邀请函设计软件 编辑:程序博客网 时间:2024/04/29 18:18

原题网址:https://leetcode.com/problems/jump-game-ii/

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.)

Note:
You can assume that you can always reach the last index.

方法一:动态规划,用jumps数组记录最小步数。

public class Solution {    public int jump(int[] nums) {        int[] jumps = new int[nums.length];        int far = 0;        for(int i=0; i<nums.length && far<nums.length-1; i++) {            for(int j=Math.min(i+nums[i], nums.length-1); j>far; j--) jumps[j] = jumps[i] + 1;            far = Math.max(far, Math.min(i+nums[i], nums.length-1));        }        return jumps[nums.length-1];    }}

方法二:动态规划,节省空间!

public class Solution {    public int jump(int[] nums) {        if (nums == null || nums.length <= 1) return 0;        int from = 0, to = 1;        for(int step = 1; ; step ++) {            int nextTo = to;            for(int i=from; i<to; i++) {                nextTo = Math.max(nextTo, i + nums[i] + 1);                if (nextTo >= nums.length) return step;            }            from = to;            to = nextTo;        }    }}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 吃了发霉的面包怎么办 种的韭菜有蛆怎么办 活狗身上长蛆虫怎么办 狗身上会有蛆虫怎么办 狗身上长满了蛆怎么办 房间墙上有很多小虫子怎么办 床上有许多小虫子怎么办? 店里有许多小虫子怎么办 房间潮湿有很多小虫子怎么办 家里潮湿墙上发霉长小虫怎么办? 房间有小飞虫子怎么办 狗被灭虫剂喷了怎么办 吃鸡玩久了手机屏幕很涩怎么办 超东卧室太阳晒怎么办 床头上的布破了怎么办 老年机全静音了怎么办 老年机手机不亮怎么办 70岁老人耳朵聋怎么办 血压太低了头晕怎么办 血压高忽然变低怎么办 血压高眼睛红了怎么办 高血压200降不下去.怎么办 高血压吃药降不下来怎么办 合肥房子卖了户口怎么办 吃了粽子胃难受怎么办 突然血压高怎么办需要吃药吗? 胃一阵阵疼然后拉肚子怎么办 橱子和墙壁不平怎么办 复印选项是英文不认识怎么办 防盗门锁与门框结合不好怎么办 仿瓷涂料墙壁脏了怎么办 油笔画到墙纸上怎么办 水笔画在墙纸上怎么办 屋里有股石灰味怎么办 厨房太阳对着晒怎么办 房子有太阳西斜怎么办 房子晒到太阳很热怎么办 房子被太阳热了怎么办 房间西晒窗帘不遮光怎么办 新建房屋一面墙体有裂缝怎么办 卫生间地砖缝隙出现渗水怎么办