• 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 of adjacent digits x and ysatisfy x <= y.)

     

    Example 1:

    Input: N = 10
    Output: 9
    

     

    Example 2:

    Input: N = 1234
    Output: 1234
    

     

    Example 3:

    Input: N = 332
    Output: 299

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    i - 1的时候不能退到0,最多退到1

    [思维问题]:

    完全没思路啊

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    数字转字符串要用String.valueOf(N),而不是(string)强制转换

    [一句话思路]:

    前一位数比较大就先标记,后面都改成9

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. mark需要初始化为最后一位数

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    大不了前面位上的数-1,后面都是9

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [算法思想:迭代/递归/分治/贪心]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

     [是否头一次写此类driver funcion的代码] :

     [潜台词] :

    class Solution {
        public int monotoneIncreasingDigits(int N) {
            //corner case
            if (N <= 9) return N;
            
            //initialization: digits, mark
            char[] digits = String.valueOf(N).toCharArray();
            int mark = digits.length - 1;
            
            //for loop and get the bigger num from i - 1
            for (int i = digits.length - 1; i > 0; i--) {
                if (digits[i] < digits[i - 1]) {
                    mark = i - 1;
                    digits[i - 1]--;
                }
            }
            
            //change the later nums into 9
            for (int j = mark + 1; j < digits.length; j++) {
                digits[j] = '9';
            }
            
            //return
            return Integer.parseInt(new String(digits));
        }
    }
    View Code
  • 相关阅读:
    通过pwndbg看看c中局部变量是如何在stack上放置的 此外 printf %n的作用终于弄明白了
    pip 安装过慢 使用清华源 加速
    mac 10.15.6 安装 IDA
    使用机器学习检测命令行混淆
    安全技能树简版
    栈溢出 hack 入门例子 hello world
    201116西瓜书机器学习系列---8、集成学习
    legend2---某些js代码电脑浏览器支持,手机浏览器不支持的调试
    legend2---做题页的每个题目对应的答案重点标颜色
    legend2---jquery重新渲染某元素
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9540084.html
Copyright © 2020-2023  润新知