博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Jump Game II
阅读量:4075 次
发布时间:2019-05-25

本文共 1828 字,大约阅读时间需要 6 分钟。

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

Java代码:

public class Solution {    public int jump(int[] A) {    int count = 0, max = 0;    for (int i = 0, nextMax = 0; i <= max && i < A.length - 1; i++) {        nextMax = Math.max(nextMax, i + A[i]);        if (i == max) {            max = nextMax;            count++;        }    }    // if there is no way to get to the end, return -1    return max >= A.length - 1 ? count : -1;}}
上述代码参考leetcode官网的解答

代码分析:

Hi All, below is my AC solution:

public int jump(int[] A) {    int maxReach = A[0];    int edge = 0;    int minstep = 0;        for(int i = 1; i < A.length; i++) {        if (i > edge) {            minstep += 1;            edge = maxReach;            if(edge > A.length - 1)                return minstep;        }        maxReach = Math.max(maxReach, A[i] + i);        if (maxReach == i):            return -1;    }        return minstep;}

When iterate the array, I set an edge for the Search phase, which means that if I exceeds the edge, the minstep must add one and the maxReach will be update. And when the last index is within the range of the edge, output the minstep.

[2, 3, 1, 1, 4]

First, the edge is 0; Second, after start iterate the array, it exceeds the edge 0 when reaching the A[0] and update the edge to 2; Third, after it reach the A[2], it exceeds the edge 2 and update the new edge to the maxReach 4. Finally, end of the array is inside the edge, output the minstep.

 

转载地址:http://jsuni.baihongyu.com/

你可能感兴趣的文章
linux内核内存管理(zone_dma zone_normal zone_highmem)
查看>>
将file文件内容转成字符串
查看>>
循环队列---数据结构和算法
查看>>
优先级队列-数据结构和算法
查看>>
链接点--数据结构和算法
查看>>
servlet中请求转发(forword)与重定向(sendredirect)的区别
查看>>
Spring4的IoC和DI的区别
查看>>
springcloud 的eureka服务注册demo
查看>>
eureka-client.properties文件配置
查看>>
MODULE_DEVICE_TABLE的理解
查看>>
platform_device与platform_driver
查看>>
platform_driver平台驱动注册和注销过程(下)
查看>>
.net强制退出主窗口的方法——Application.Exit()方法和Environment.Exit(0)方法
查看>>
c# 如何调用win8自带的屏幕键盘(非osk.exe)
查看>>
build/envsetup.sh 简介
查看>>
Android framework中修改或者添加资源无变化或编译不通过问题详解
查看>>
linux怎么切换到root里面?
查看>>
linux串口操作及设置详解
查看>>
安装alien,DEB与RPM互换
查看>>
编译Android4.0源码时常见错误及解决办法
查看>>