LeetCode 题解工作台

单调递增的数字

当且仅当每个相邻位数上的数字 x 和 y 满足 x 时,我们称这个整数是 单调递增 的。 给定一个整数 n ,返回 小于或等于 n 的最大数字,且数字呈 单调递增 。 示例 1: 输入: n = 10 输出: 9 示例 2: 输入: n = 1234 输出: 1234 示例 3: 输入: n = 3…

category

2

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

从数字 `n` 的高位开始,找到第一个不满足 $n_{i-1} \le n_i$ 的位置 。 然后,从后往前,只要发现 $n_{i-1} \gt n_i$,就将 减 1。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

当且仅当每个相邻位数上的数字 x 和 y 满足 x <= y 时,我们称这个整数是单调递增的。

给定一个整数 n ,返回 小于或等于 n 的最大数字,且数字呈 单调递增

 

示例 1:

输入: n = 10
输出: 9

示例 2:

输入: n = 1234
输出: 1234

示例 3:

输入: n = 332
输出: 299

 

提示:

  • 0 <= n <= 109
lightbulb

解题思路

方法一:贪心

从数字 n 的高位开始,找到第一个不满足 ni1nin_{i-1} \le n_i 的位置 ii

然后,从后往前,只要发现 ni1>nin_{i-1} \gt n_i,就将 ni1n_{i-1} 减 1。

最后将位置 ii 之后的所有数字都置为 9 即可。

时间复杂度 O(logn)O(\log n),空间复杂度 O(logn)O(\log n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
    def monotoneIncreasingDigits(self, n: int) -> int:
        s = list(str(n))
        i = 1
        while i < len(s) and s[i - 1] <= s[i]:
            i += 1
        if i < len(s):
            while i and s[i - 1] > s[i]:
                s[i - 1] = str(int(s[i - 1]) - 1)
                i -= 1
            i += 1
            while i < len(s):
                s[i] = '9'
                i += 1
        return int(''.join(s))
speed

复杂度分析

指标
时间complexity is O(log n) because each digit is processed once, and space complexity is O(log n) to store the digits in an array representation of n.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Asks about handling digit violations and the greedy invariant.

  • question_mark

    Checks if you understand why setting trailing digits to 9 maximizes the number.

  • question_mark

    Looks for a clear explanation of digit-by-digit adjustments without overshooting n.

warning

常见陷阱

外企场景
  • error

    Forgetting to set all digits after a decrement to 9, breaking maximality.

  • error

    Misidentifying which digit to decrement when multiple violations exist.

  • error

    Attempting a brute-force scan of all numbers ≤ n instead of a greedy digit approach.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find the smallest monotone decreasing number ≥ n.

  • arrow_right_alt

    Compute the count of monotone increasing numbers ≤ n.

  • arrow_right_alt

    Modify the approach to work with a custom base instead of decimal digits.

help

常见问题

外企场景

单调递增的数字题解:贪心·invariant | LeetCode #738 中等