算法练习Day28 (Leetcode/Python-贪心算法)

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 nwith monotone increasing digits.

Example 1:

复制代码
Input: n = 10
Output: 9

Example 2:

复制代码
Input: n = 1234
Output: 1234

Example 3:

复制代码
Input: n = 332
Output: 299

思路,此题求小于给定的数值N的最大的单调递增序列。对于每个数位,从后向前遍历,但凡发现前一位N[i-1]比后一位N[i]大,能做的就是把后一位N[i]置9,前一位置N[i-1]-1。

python 复制代码
class Solution(object):
    def monotoneIncreasingDigits(self, n):
        """
        :type n: int
        :rtype: int
        """
        # convert int to string
        strNum = str(n)
        flag = len(strNum)
        for i in range(len(strNum)-1, 0, -1):
            if strNum[i] < strNum[i-1]:
                flag = i 
                strNum = strNum[:i-1] + str(int(strNum[i-1])-1) + strNum[i:]
        
        #for i in range(flag, len(strNum)):
        print(flag)
        strNum = strNum[:flag] + '9' * len( strNum[flag:]) 

        return int(strNum)
相关推荐
王哈哈^_^13 小时前
CV三大核心任务:目标检测、图像分割、关键点检测
人工智能·算法·yolo·目标检测·计算机视觉·视觉检测
wefg113 小时前
【数据结构】红黑树
数据结构·算法
饼瑶13 小时前
基于AutoDL远端服务复现具身智能论文OpenVLA
算法
Mr.Winter`13 小时前
无人船 | 图解基于MPC控制的路径跟踪算法(以全驱动无人艇WAMV为例)
人工智能·算法·机器人·自动驾驶·ros·路径规划
咪咪渝粮14 小时前
112.路径总和
java·数据结构·算法
高洁0114 小时前
大模型-详解 Vision Transformer (ViT) (2
深度学习·算法·aigc·transformer·知识图谱
电子_咸鱼14 小时前
高阶数据结构——并查集
数据结构·c++·vscode·b树·python·算法·线性回归
zl_dfq14 小时前
基于哈夫曼树的数据压缩算法
算法
多喝开水少熬夜14 小时前
算法-哈希表和相关练习-java
java·算法·散列表
余衫马15 小时前
聚类算法入门:像魔法一样把数据自动归类
人工智能·算法·机器学习·聚类