[抄题]:
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
.)
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
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 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)); } }