leetcode:跳跃游戏II(java贪心算法)

leetcode-hot100-14贪心算法 (Greedy Algorithm)是一种常见的优化算法,用于解决最优化问题。该算法的核心思想是每次选择当前情况下的最优解,并期望通过这些局部最优解得到全局最优解。贪心算法通常用于那些可以分解为若干个子问题,且每个子问题的最优解可以合成全局最优解的问题。贪心算法之所以有用,是因为它可以快速地做出决策,并能在某些问题上实现较高的效率,避免了回溯与暴力解法的复杂度。。每一步做出决策时,贪心算法并不考虑未来的选择。它的核心假设是:通过局部最优的选择,最终能得到全局最优的解。 阅读详情
package LeetCode;

public class Jump {
    public int jump(int[] nums) {
        //跳跃次数
    int cont=0;
    //跳出条件
    int n=nums.length;
    //为了保存每次可以到达的地方
    int i=0;
    int max=0;
    int s=0;
       while (max<n-1){
            cont++;
            int a=max;
             i=s;
            for (;i<=a;i++){
                max=Math.max(max,i+nums[i]);
                if(max!=a)s=i;
            }
       }
       return cont++;
    }

    public static void main(String[] args) {
        Jump a=new Jump();
        int[] b={2,3,1,1,4};
        System.out.println(a.jump(b));
    }
}

 

LeetCode 55 & 45:跳跃游戏与跳跃游戏 II - 贪心算法详解 跳跃游戏系列是LeetCode中经典的贪心算法问题,考察对数组遍历和最优策略的理解。本文将详细解析55题(跳跃游戏)和45题(跳跃游戏 II)的解决方案,通过图解和Java实现帮助读者掌握贪心算法的应用。 阅读详情

相关推荐

LeetCode045——跳跃游戏II

我的LeetCode代码仓:https://github.com/617076674/LeetCode 原题链接:https://leetcode-cn.com/problems/jump-game-ii/description/ 题目描述: 知识点:贪心算法 思路一:回溯法(在LeetCode中提交会超时) 回溯法的思想很简单,寻找到所有能到达数组的最后一个位置的可能路径,计算其最...

清风阁 2991

[Java·算法·中等] LeetCode 45. 跳跃游戏 II 详细解读

这个算法具有线性时间复杂度 O(n),其中 n 是数组的长度,因为只需一次遍历数组。,分别表示当前跳跃范围的结束位置和在这个范围内可达的最远位置。从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。换句话说,如果你在 nums[i] 处,你可以跳转到任意。你可以使用贪心算法来找到到达数组的最后一个元素的最小跳跃次数。输入: nums = [2,3,1,1,4]解释: 跳到最后一个位置的最小跳跃数是 2。就表示到达数组最后一个元素的最小跳跃次数。,表示下一次跳跃的范围。

double222222的博客 685

力扣面试经典算法150题:跳跃游戏 II

力扣面试经典算法150题:跳跃游戏 II

weixin_48668564的博客 916

45. 跳跃游戏 II(力扣LeetCode)

如果移动下标达到了当前这一步的最大覆盖最远距离了,还没有到终点的话,那么就必须再走一步来增加覆盖范围,直到覆盖范围覆盖了终点。贪心的思路,局部最优:当前可移动距离尽可能多走,如果还没到终点,步数再加一。从图中可以看出来,就是移动下标达到了当前覆盖的最远距离下标时,步数就要加一,来增加覆盖距离。最后的步数就是最少步数。思路虽然是这样,但在写代码的时候还不能真的能跳多远就跳多远,那样就不知道下一步最远能跳到哪里了。从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。

m0_73841621的博客 1452

跳跃游戏 II - 题解分析与实现(Java)

在这篇文章中,我们将讨论 LeetCode 上的跳跃游戏 II 题目,并提供相应的 Java 实现代码。跳跃游戏 II 是一道经典的贪心算法问题,要求我们计算到达数组末尾所需的最少跳跃次数。我们可以通过维护两个变量来解决问题:当前覆盖的最远位置和下一步的最远位置。我们遍历数组,更新这两个变量,直到覆盖的最远位置达到数组末尾。数组中的每个元素代表你在该位置可以跳跃的最大长度。目标是使用最少的跳跃次数到达数组的最后一个位置。这是一个高效且简洁的解决方案,可以在给定的时间限制内解决大多数测试用例。

2301_79365003的博客 227

基于IC动态加权的机器学习多因子选股策略:从模型融合到实战回测

在量化投资领域,多因子选股模型通过挖掘市场数据中的有效信号来预测股票收益。其核心原理在于利用统计学与机器学习算法,从海量因子中识别出与未来收益具有稳定相关性的特征。这一技术的核心价值在于将主观投资决策转化为系统化、可重复的客观过程,从而在控制风险的前提下追求超额收益。其典型应用场景包括股票阿尔法策略构建、Smart Beta产品设计以及资产配置中的股票筛选环节。本文聚焦于如何通过信息系数(IC)这一关键指标,动态融合Ridge回归、MLP神经网络和随机森林等多个预测模型,构建一个能够自适应市场风格轮动的选股

weixin_34216614的博客 457

Java | Leetcode Java题解之第45题跳跃游戏II

Java | Leetcode Java题解之第45题跳跃游戏II

m0_57195758的博客 659

基于Python的微信聊天记录分析——数据获取

本篇为“基于Python的微信聊天记录分析”第一篇,主要涉及数据获取,包括Python环境配置、WeChatMsg项目配置和运行、获取聊天记录等内容,流程简单、比较基础,后续这个系列会涉及基于Python的数据处理、统计分析、NLP技术等内容。希望和大家多多交流,共同进步!

Henryli1202的博客 1万+

贪心算法之跳跃游戏Ⅱ--附java代码

贪心的思路,局部最优:当前可移动距离尽可能多走,如果还没到终点,步数再加一。整体最优:一步尽可能多走,从而达到最少步数。

qq_57687220的博客 349

显示发光---LED/OLED/LCD/AMOLED原理图介绍

显示发光不同原理介绍

Classical_Man的博客 2858

信号转换为图像 时域频域分析

一维信号如何转化为图像?深度学习如何学习 1.当然,直接1d卷积也是可以的。 2. 以信号强度的数值作为纵坐标,以时间为横坐标绘制信号点就可以了。 周霖那个即是 要看看代码是如何做的, 即使是单导联 5000个点,怎么变成50005000的分辨率的 3. 直接把多通道的一维信号合并成二维图像,然后直接按图像卷积的方法去做~~ 2225000这样一个图 ~可以看看语音处理的相关Net,其中比较...

王不留行嘿呦嘿 2万+

Java版LeetCode热题100之跳跃游戏 II:贪心算法求最少跳跃次数的深度解析

问题本质:线性最短路径问题最优解法正向贪心算法,一次遍历关键思想:维护当前跳跃边界和下一步最远位置时间复杂度OnO(n)On空间复杂度O1O(1)O1适用场景:任何需要在线性结构中求最少步骤的问题。

吾为热爱计科,致力于知识分享的践行者,此博客是我在这条道路上留下的足迹。 719

39-Halcon-- fit_primitives_object_model_3d函数功能(从3D数据中提取几何基元)

Halcon算子fit_primitives_object_model_3d工业应用精要 该算子专为3D几何特征提取设计,支持平面、球体、圆柱等基元拟合。核心优势: 参数化输出:返回几何元素的数学参数(如平面方程、球心半径) 智能控制:通过max_dist、min_size等参数调节拟合精度 工业场景适配:针对薄壁件、孔系等提供专用优化方案 典型应用流程: 数据预处理(点云降噪/采样) 基元类型与参数设置 多阶段拟合(先平面后圆柱) 几何精度验证 误差控制在0.1%-1.2%范围内(视点云密度而定),适用于

weixin_45590420的博客 1163

LeeCode( 优先队列)45_跳跃游戏 II

LeeCode( 贪心算法)45_跳跃游戏 II 题目: 给定一个非负整数数组,你最初位于数组的第一个位置。 数组中的每个元素代表你在该位置可以跳跃的最大长度。 你的目标是使用最少的跳跃次数到达数组的最后一个位置。 示例: 输入: [2,3,1,1,4] 输出: 2 解释: 跳到最后一个位置的最小跳跃数是 2。 从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。 说明: 假设你总是可以到达数组的最后一个位置。 来源:力扣(LeetCode) 链接:https://lee

u013456390的博客 240

Linux存储软件栈剖析之第5篇:F2FS文件系统

F2FS是三星专为NAND闪存设计的开源文件系统,通过异地更新、磨损均衡等机制优化闪存特性。其架构采用层次化存储管理(Block→Segment→Section→Zone)和多日志区域设计,基于数据热度分类(热/温/冷数据)提升性能。核心创新包括节点地址表(NAT)解决级联更新问题,以及基于成本的垃圾回收算法。F2FS通过检查点机制确保崩溃一致性,并利用并行访问能力充分发挥闪存性能优势,显著降低写放大效应,延长设备寿命。

指尖动听知识库 199

通过InoDriverShop伺服调试软件连接汇川SV660F系列伺服的具体方法示例

通过InoDriverShop伺服调试软件连接汇川SV660F系列伺服的具体方法示例

Robot_PLC_HMI_Automation 1万+

【代码训练营】day32 | 122.买卖股票的最佳时机II & 55. 跳跃游戏 & 45.跳跃游戏II

代码训练营 day32

weixin_48494936的博客 142

TIA博途WINCC的触摸屏VB脚本入门指南(嵌入式)

通过编写事件处理程序,您可以响应触摸屏元素的各种事件,并实现自定义的功能。本文将为您提供TIA博途WINCC触摸屏VB脚本的入门指南,帮助您了解基本的脚本编写和嵌入式开发。假设我们有一个名为"Button1"的按钮元素,当用户点击该按钮时,触发相应的事件处理程序,并在触摸屏上显示一条消息。然后回到触摸屏界面编辑器,在按钮元素的属性窗口中找到"按下"事件,并选择刚才创建的脚本文件作为事件处理程序。现在,当用户点击按钮时,触摸屏将执行相应的事件处理程序,并显示一条消息框,内容为"按钮被点击了!

CodeSageX的博客 4424

每日一题:45. 跳跃游戏 II

每日一题:45. 跳跃游戏 II

雨雪大帝 161

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

代码随想录算法训练营_day28

局部最优推出全局最优,找不出反例,试试贪心!如图:i 每次移动只能在 cover 的范围内移动,每移动一个元素,cover 得到该元素数值(新的覆盖范围)的补充,让 i 继续移动下去。而 cover 每次只取 max(该元素数值补充后的范围, cover 本身范围)。如果 cover 大于等于了终点下标,直接 return true 就可以了。

qq_43745961的博客 695

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

代码随想录算法训练营第二十八天|LeetCode 122, 55,45

贪心算法

iwtup的博客 143

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

leetcode 45. 跳跃游戏 II(贪心)

题目 给定一个非负整数数组,你最初位于数组的第一个位置。 数组中的每个元素代表你在该位置可以跳跃的最大长度。 你的目标是使用最少的跳跃次数到达数组的最后一个位置。 假设你总是可以到达数组的最后一个位置。 示例 示例 1: 输入: [2,3,1,1,4] 输出: 2 解释: 跳到最后一个位置的最小跳跃数是 2。 从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。 示例 2: 输入: [2,3,0,1,4] 输出: 2 思路 begin为可选区块的初始位置,end为可选区块

腿毛一米五 226

【JAVA算法|hot100】贪心算法类型题目详解笔记

本文总结了LeetCode热题100中4道贪心算法题目的解题思路。121题通过记录历史最低价计算最大利润;55题用最远可达位置判断能否跳到终点;45题通过记录当前跳跃范围计算最小跳跃次数;763题利用字母最后出现位置划分字符串片段。这些题目都体现了贪心算法的核心思想:通过局部最优选择逐步达到全局最优解。解题关键在于如何定义和更新关键的边界值(如最低价、最远位置等),从而在遍历过程中做出最优决策。

2303_80850235的博客 338

2021-06-17

877. 石子游戏 思路 考虑dp[i][j]数组是两者的石子之差,i,j表示不同区间情况下的差值。 那么对每个区间,我们可以考虑: 对于先手,取第一个数/取最后的数:剩下的后手变成先手,区间缩短求其分差 由上可以看出,分差是有正负的,所以我们最后考虑dp[1][n]的正负即可 public boolean stoneGame(int[] piles) { int n = piles.length; int[][] dp = new int[n + 2][n + 2];

weixin_42180334的博客 248

《LeetCode力扣练习》代码随想录——贪心算法(跳跃游戏 II---Java)

《LeetCode力扣练习》代码随想录——贪心算法(跳跃游戏 II---Java)

XRT_knives的博客 344

力扣最热一百题——跳跃游戏II

全网最热一百题——超详细解释,多方位分析,新手也能学会!!!

WenJGo的博客 1266
上一篇: leetcode:字符串相乘(java)
下一篇: leetcode:全排列(java回溯)
ArchitectDream
博客等级 码龄9年 48粉丝 288原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值