738.单调递增的数字
- 确定贪心思想: 贪心就是一次遍历,然后获取每一次遍历下符合条件的解。对于给定数值98,一旦出现strNum[i - 1] > strNum[i]的情况(非单调递增),首先想让strNum[i - 1]–,然后strNum[i]给为9,这样这个整数就是89,即小于98的最大的单调递增整数。
- 确定遍历顺序: 分析如果向后遍历和向前遍历,两者之间会有什么不同,如果向前遍历容易使得修改完后边的值之后,前边的值发生变化。如果向后遍历可以很好的解决这一问题。
class Solution:
def monotoneIncreasingDigits(self, n: int) -> int:
lst = list(str(n))
for i in range(len(lst)-1,0,-1):
if int(lst[i]) < int(lst[i-1]):
lst[i-1] = str(int(lst[i-1])-1)
lst[i:] = '9' * (len(lst) - i)
return int(''.join(lst))
总结
- 主要有摆动序列、重叠区间、前后序列双重考虑等思想。
