LeetCode 738. Monotone Increasing Digits
考点 | 难度 |
---|---|
Greedy | Easy |
题目
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.
思路
从右向左找到第一个不满足monotone increase的数字,前一位减一,之后所有位都是9
1 reverse array
2 找到最左边的inverted数字,如果是重复的,找到重复的起点
3 减1,后面都改成9
4 变回int
答案
class Solution(object):
def monotoneIncreasingDigits(self, N):
if N < 10: return N
n, inv_index = N, -1
num = [int(d) for d in str(n)[::-1]]
for i in range(1, len(num)):
if num[i] > num[i - 1] or (inv_index != -1 and num[inv_index] == num[i]):
inv_index = i
if inv_index == -1: return N
for i in range(inv_index): num[i] = 9
num[inv_index] -= 1
return int(''.join([ str(i) for i in num[::-1]]))