Monotone Increasing Digits问题及解法
来源:互联网 发布:美股数据下载 编辑:程序博客网 时间:2024/06/05 23:42
问题描述:
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
.)
示例:
Input: N = 10Output: 9
Input: N = 1234Output: 1234
Input: N = 332Output: 299
Note: N
is an integer in the range [0, 10^9]
.
问题分析:
从左到右找到相邻两个数字中digit[i] > digit[i+1]的索引i,对于i+1到digits.size()的数字全部置为9;
对于j在i到0之间依次找到digits[j] > digits[j + 1],设置digits[j + 1] = 9;digits[j]--;其他情况直接跳出循环。
过程详见代码:
class Solution {public: int monotoneIncreasingDigits(int N) { int n = N;if (N < 10) return N;if (N == 10) return 9;vector<int> digits;while (N){digits.push_back(N % 10);N /= 10;}reverse(digits.begin(), digits.end());int i = 0;for (; i < digits.size() - 1; i++){if (digits[i] > digits[i + 1]){digits[i]--;break;}}if (i == digits.size()) return n;for (int j = i + 1; j < digits.size(); j++) digits[j] = 9;for (int j = i - 1; j >= 0; j--){if (digits[j] > digits[j + 1]){digits[j + 1] = 9;digits[j]--;}else break;}int res = 0;for (int t = 0; t < digits.size(); t++){res = res * 10 + digits[t];}return res; }};
阅读全文
0 0
- Monotone Increasing Digits问题及解法
- 738. Monotone Increasing Digits
- 738. Monotone Increasing Digits
- Leetcode 738. Monotone Increasing Digits
- LWC 61:738. Monotone Increasing Digits
- LeetCode刷题 | 738. Monotone Increasing Digits
- LeetCode—738. Monotone Increasing Digits
- Increasing Subsequences问题及解法
- leetcode weekly contest 61 ( 738. Monotone Increasing Digits )
- 【算法分析与设计】【第十四周】738. Monotone Increasing Digits
- Leetcode 738. Monotone Increasing Digits(算法分析week16)
- Longest Continuous Increasing Subsequence 问题及解法
- Longest Increasing Subsequence问题及解法
- Increasing Triplet Subsequence问题及解法
- Count Numbers with Unique Digits问题及解法
- Reconstruct Original Digits from English 问题及解法
- Heaters问题及解法
- Permutations问题及解法
- 图的邻接链表实现下的搜索两点之间所有路径的算法
- 如何查看进程/服务是否启动
- coursera课程learning how to learn的主要内容-学会学习(一)
- POJ 1017 Packets
- Linux之命令scp
- Monotone Increasing Digits问题及解法
- 什么是无侵入
- Servlet
- 49. Group Anagrams
- php中的函数
- Linux 进程间通信2
- Nicescroll滚动条插件的用法
- 解决Mac环境下vim中文乱码&转码问题
- git如何上传所有的新文件