算法-Monotone Increasing Digits-单调递增的数字

字节面试题 小于n的最大数 ②第二种情况为找到这个最大数,且最大数小于当前位的数,则将数压入结果栈,并且后续的位应全部用所给数组nums中的最大元素来作为选择,然后退出最外层循环,返回结果。①出栈回溯前面的位,找到最大且小于当前回溯位数字的元素(而不包括等于当前回溯位数字),如果找到这样的元素,压入结果栈,后续位全部用最大元素填充。对目标数进行遍历,以贪心的方式在所给数组nums中找出小于等于当前位并且最大的数。①第一种情况为找到这个最大数,且最大数等于当前位的数,则将数压入结果栈中。II.不能找到这样的数。 阅读详情

1、题目描述

给定一个非负整数 N,找出小于或等于 N 的最大的整数,同时这个整数需要满足其各个位数上的数字是单调递增。
(当且仅当每个相邻位数上的数字 x 和 y 满足 x <= y 时,我们称这个整数是单调递增的。)

示例 1:
输入: N = 10
输出: 9

示例 2:
输入: N = 1234
输出: 1234

示例 3:
输入: N = 332
输出: 299

2、题目分析

  • 递增的数字是什么?前一位的要小于等于后一位的
  • 当数字只有一位的时候,本身就是递增的数字
  • 当数字是递增的时候,直接返回该数字
  • 当数字是逆序的时候,进行操作,如何保证是最大的呢?观察可以看到,如果坐标i-1的值 < i的值,将i-1的值-1,i以及后边的值都换成 贪心思想
  • 如何操作单个的int型数字的每位比较方便?转换成String类型再转换成数组类型进行操作,最后进行转型

3、代码实现

class Solution {
    public int monotoneIncreasingDigits(int N) {
     /**
     * 思路:
     *  从右向左扫描数字,若发现当前数字比其左边一位(较高位)小,
     *  则把其左边一位数字减1,并将该位及其右边的所有位改成9
     */
        char[] a = String.valueOf(N).toCharArray();
        if(a.length < 2) return N;
        for(int i = a.length - 2;i >= 0;i--){
            if(a[i] - '0' > a[i + 1] - '0'){
                a[i] = (char)(a[i] -'1' +'0');
                for(int j = i + 1;j < a.length;j++){
                    a[j] = '9';
                }
            }
        }
        return Integer.parseInt(new String(a));
    }
}
  • 赋值9可以优化一下,记录一下最前边的9的位置,下次只赋值到这个位置

4、复杂度分析

  • 时间复杂度:O(logN) ,N是数字,其位数是logN
  • 空间复杂度:O(logN),同上
经典面试题-小于N的最大数 小于N的最大值 阅读详情

相关推荐

leetcode之贪心算法刷题总结4

leetcode之贪心算法刷题总结4 贪心算法(又称贪婪算法)是指,在对问题求解时,总是做出在当前看来是最好的选择,就能得到问题的答案。贪心算法需要充分挖掘题目中条件,没有固定的模式,解决有贪心算法需要一定的直觉和经验。 贪心算法不是对所有问题都能得到整体最优解。能使用贪心算法解决的问题具有「贪心选择性质」。「贪心选择性质」严格意义上需要数学证明。能使用贪心算法解决的问题必须具备「无后效性」,即某个状态以前的过程不会影响以后的状态,只与当前状态有关。 1-最长快乐字符串 题目链接:题目链接戳这里!!! 思路

nuist_NJUPT的博客 1081

【LeetCode】-贪心算法

文章目录前言一、组合二、摆动序列 前言 初识LeetCode与算法,将在此系列文章里面,记录自己的算法学习经历,前期主要是监督自己学习打卡,后期我会将自己对知识的理解,慢慢补充到文章当中,希望大家能在阅读我的文章中,有所收获。该系列文章的刷题顺序以代码随想录为线索。 一、组合 题目: 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。 对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j

银尘博客 6191

超越界面设计:GUI Guider与LVGL在STM32F103上的系统集成与架构思考

本文探讨了GUI Guider与LVGL在STM32F103微控制器上的系统集成与架构设计,重点分析了工程模块化组织、内存管理优化、硬件驱动接口设计以及FreeRTOS多任务集成。针对STM32F103ZET6的资源限制,提供了实用的移植策略和性能优化方案,帮助开发者构建高效、可维护的嵌入式GUI系统。

j2k3l4的博客 921

力扣LeetCode-贪心算法

贪心算法 基本知识 1.思想 基于局部最优的选择逐渐推导出全局最优解 2.一般步骤 将问题分解为若干个子问题; 找出合适的贪心策略; 求解每一个子问题的最优解; 将局部最优解合成为全局最优解; 典型例题 1. LeetCode 376. 摆动序列 题目 如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为 摆动序列 。第一个差(如果存在的话)可能是正数或负数。仅有一个元素或者含两个不等元素的序列也视作摆动序列。 例如, [1, 7, 4, 9

weixin_56005963的博客 2981

电力电子技术文章:ACOT控制模式在Buck变换器中的频率稳定性分析

本文深入分析了ACOT控制模式在Buck变换器中实现频率稳定性的原理与优势。通过对比传统COT模式,阐述了ACOT如何通过自适应调整导通时间,将开关频率锁定在设定值,从而有效应对输入电压与负载变化。文章还探讨了其在轻载DCM模式下的高效与平滑切换特性,并提供了关键的设计考量与实战指南。

cc789的博客 1149

SAP 运费处理方式

从直接的处理方式上看,情况1/2/3可以将运费记账到物料成本中,但情况4/5/6是直接记账到成本对象中,具体是要体现在损益表中,还是要结转到物料成本中,可依据业务要求进行好处理。如果体现在损益表中,不需要多过多额外的操作,如果要体现在物料成本中心,则需要再进行一系列的处理,最终将金额结转到物料成本中。因为在创建采购订单时不知道具体运费,可以不维护运费,只需要维护材料价格。:创建采购订单时,运费是由供应商承担,很多时候是包含在材料报价中,这种情况不需要专门针对运费进行处理,材料价格中已包含运费。

weixin_44506537的博客 3371

Day31: 56. Merge Intervals, 738. Monotone Increase Digits

3、后面的元素每一组的左边届都与res数组最后一组元素的右边界进行比较:若重叠,更新res数组中最后一组元素的右边界值;若不重叠,将这组元素插入res数组。解题思路:从后往前遍历每一位数,如果前一位数大于当前位数,则将前一位数减1,后面所有位数都改成9。时间复杂度:O(nlogn) 排序所需。空间复杂度:O(logn) 排序所需。时间复杂度:O(N),N为数字的长度。做题情况:用的暴力解法,超时了。1、排序,尽可能让空间重叠。题目难度:Medium。题目难度:Medium。空间复杂度:O(N)

2401_83154344的博客 463

告别ROS1思维:在ROS2 Humble上,用Python搞定MoveIt2机械臂控制的完整流程

本文详细介绍了在ROS2 Humble环境下使用Python控制MoveIt2机械臂的完整流程。从环境配置、架构变革到实战操作,涵盖URDF适配、Action接口编程及性能优化技巧,帮助开发者高效迁移ROS1项目至ROS2平台,实现工业级机械臂控制。

weixin_30352645的博客 449

day31 (代码随想录补卡)56. 合并区间|738.单调递增的数字

738.单调递增的数字。

qq_38788700的博客 342

PCB高速信号换层孔新技术:VECS(Vertical Conductive Structure Technology)解析

摘要:垂直导电结构(VeCS)是一种新型PCB互连技术,由平板信号走线和椭圆形接地层构成半同轴结构,相比传统过孔具有显著优势。通过全波仿真和实测验证,VeCS展现出更好的阻抗连续性、更低的插入损耗和回波损耗,以及优异的串扰抑制能力。其椭圆形接地结构能有效隔离电磁干扰,在相同布线密度下远端串扰比传统过孔降低约50%。VeCS制备工艺与传统PCB工艺兼容,无需新增设备,且能实现更高密度互连。测试结果显示,2.5英寸带状线通道中VeCS结构的信号完整性表现明显优于传统过孔,为高速数字系统提供了更可靠的垂直互连解决

小孟同学的博客 198

纯方位观测下的三维定位,IV-PLKF(Inverse Velocity-Weighted Pseudo-Linear Kalman Filter)

在现代定位系统中,纯方位观测因其无需测距设备的优势,在无线通信、无人机导航和室内定位等领域备受关注。本文深入探讨基于算法的三维定位方法,并提供完整的MATLAB仿真例程。

985工科博士毕业,专攻定位、导航和滤波等算法研究。从业10年,主要使用MATLAB 672

738. Monotone Increasing Digits(单调递增的数字)

** 题目** 分析: 首先分析题目给出的条件,输出的数不能大于输入的数,且输出的数的各个位数单调递增的。解决这类条件限定题目,可以有两种思路: 在位数等确定的情况下可以使用for循环以及if else进行筛选和判断。 在位数不确定的情况下,一般通过对原数组的遍历修改,达到目标。 这两种情况都需要对条件充分认识,后者会更加趋向于对规律的判断。我们选择第二种方法,输入的位数是不确定的,输出的位数...

马一凡的博客 378

OpenClaw与大语言模型(Claude/GPT/MiniMax)的集成架构与最优配置策略

摘要 本文探讨了OpenClaw框架与大语言模型(Claude/GPT/MiniMax)的集成架构与优化策略。大语言模型具有强大的自然语言处理能力,但集成面临API成本、响应延迟、上下文管理等挑战。OpenClaw采用分层架构设计,包括用户界面层、对话管理层、提示工程层、模型适配层和API调用层,支持多模型切换、智能对话管理和成本控制。系统通过模型适配层实现不同API的统一调用,并提供缓存、监控等优化机制。该集成方案能够充分发挥大语言模型的优势,为本地AI助理提供更智能的服务。

一键难忘的博客 1693

Monotone Increasing Digits

738.Monotone Increasing Digits Given a non-negative integerN, find the largest number that is less than or equal toNwith monotone increasing digits. (Recall that an integer hasmonotone increasi...

Czyaun的博客 233

GEE聚类分析:基于sentinel-2 影像进行 K-Means 聚类分析

这篇博客介绍了如何使用 Google Earth Engine (GEE) 进行 K-Means 聚类分析,以识别感兴趣区域(ROI)内的不同地表覆盖类型。文章详细说明了从定义用户参数、准备参考区域、加载和预处理 Sentinel-2 图像,到训练 K-Means 聚类器并对图像进行聚类的完整流程。代码示例展示了如何设置参数、采样像素数据、训练聚类器,并将结果可视化。最后,还提供了将聚类结果导出到 Google Drive 的选项。通过该教程,用户可以掌握在 GEE 平台上进行地理数据聚类分析的基本方法。

此星光明博客 262

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

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

《每日一题》738. Monotone Increasing Digits 单调递增的数字

给定一个非负整数 N,找出小于或等于 N 的最大的整数,同时这个整数需要满足其各个位数上的数字是单调递增。 (当且仅当每个相邻位数上的数字 x 和 y 满足 x <= y 时,我们称这个整数是单调递增的。) 示例 1: 输入: N = 10 输出: 9 示例 2: 输入: N = 1234 输出: 1234 示例 3: 输入: N = 332 输出: 299 说明: N 是在 [0, 1

Alex 509

深度学习工具包 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] 738. Monotone Increasing Digits

Description Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only ...

Learning from the mistakes 297

IDEA的使用指南

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

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

【LeetCode】738. Monotone Increasing Digits 单调递增的数字(Medium)(JAVA)每日一题

【LeetCode】738. Monotone Increasing Digits 单调递增的数字(Medium)(JAVA) 题目地址: https://leetcode-cn.com/problems/monotone-increasing-digits/ 题目描述: Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits

qq_16927853的博客 200

[leetcode]738. Monotone Increasing Digits

[leetcode]738. Monotone Increasing Digits Analysis 放假回家效率果然打折—— [每天刷题并不难0.0] Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits...

weixin_32135877的博客 157

[leetcode]贪心算法之Monotone Increasing Digits

贪心算法之Monotone Increasing Digits题干答案反思 题干 Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone i...

crabstew的博客 237

LeetCode //C - 738. Monotone Increasing Digits

An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y. Given an integer n, return *the largest number that is less than or equal to n with monotone increasing digits.*

Made in Code 1516

738. Monotone Increasing Digits

Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.(Recall that an integer has monotone increasing digits if and only if each pair o

xdhc的博客 307

LeetCode.738 Monotone Increasing Digits(单调递增的数)

1.题目 Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.) 2.样

侠客小虎的博客 249

[Swift]LeetCode738. 单调递增的数字 | Monotone Increasing Digits

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:https://www.cnblogs.com/stren...

weixin_30640291的博客 161

Leetcode 738. Monotone Increasing Digits

Leetcode 738. Monotone Increasing Digits

u013898524的博客 794
上一篇: 算法-Group Anagrams-字母异位词分组
下一篇: 算法-Word Pattern-单词规律
酱油瓶啤酒杯
博客等级 码龄8年 35粉丝 135原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值