❇️Day 37 第八章 贪心算法 part06
✴️今日任务
❇️738.单调递增的数字
- 题目链接:https://leetcode.cn/problems/monotone-increasing-digits/
- 视频讲解:https://www.bilibili.com/video/BV1Kv4y1x7tP
- 文章链接:https://programmercarl.com/0738.%E5%8D%95%E8%B0%83%E9%80%92%E5%A2%9E%E7%9A%84%E6%95%B0%E5%AD%97.html
自己的思路
- 先把数字转换成数组,利用一个Array数组
- 先从右往左遍历,找出从右往左单调递减最大的数
- 好像不太行
- eg:677440
- 会变成 333339
- 直接从左往右遍历,遇到后面小的数当前数-1,后面的数全变成9
- 再从当前数往前遍历,前面的数如果更大就把当前数变成9,前面的数-1
自己的代码(✅通过94.27%)
class Solution {
public int monotoneIncreasingDigits(int n) {
if(n == 0) return 0;
int res = 0;
LinkedList<Integer> nums = new LinkedList<>();
while(n != 0){
nums.push(n % 10);
n /= 10;
}
int[] nums1 = new int[nums.size()];
nums1[nums.size() - 1] = nums.get(nums.size() - 1);
for (int i = 0; i < nums.size() - 1; i++) {
if(nums.get(i + 1) < nums.get(i)){
nums1[i] = nums.get(i) - 1;
for (int j = i + 1; j < nums1.length; j++) {
nums1[j] = 9;
}
int x = i;
while(x > 0){
if(nums1[x] < nums1[x - 1]){
nums1[x] = 9;
nums1[x - 1] --;
}
x --;
}
break;
}else{
nums1[i] = nums.get(i);
}
}
int num = 1;
for (int i = nums1.length - 1; i >= 0; i --) {
res += nums1[i] * num;
num *= 10;
}
return res;
}
}
随想录思路
- 直接用字符串而不是数组
随想录代码
class Solution {
public int monotoneIncreasingDigits(int n) {
String s = String.valueOf(n);
char[] chars = s.toCharArray();
int start = s.length();
for (int i = s.length() - 2; i >= 0; i--) {
if (chars[i] > chars[i + 1]) {
chars[i]--;
start = i+1;
}
}
for (int i = start; i < s.length(); i++) {
chars[i] = '9';
}
return Integer.parseInt(String.valueOf(chars));
}
}
☑️968.监控二叉树 (可以跳过)
- 本题是贪心和二叉树的一个结合,比较难,一刷大家就跳过吧。
- 题目链接:https://leetcode.cn/problems/binary-tree-cameras/
- 视频讲解:https://www.bilibili.com/video/BV1SA411U75i
- 文章链接:https://programmercarl.com/0968.%E7%9B%91%E6%8E%A7%E4%BA%8C%E5%8F%89%E6%A0%91.html
🈴总结
- 可以看看贪心算法的总结,贪心本来就没啥规律,能写出个总结篇真的不容易了。
- 文章链接:https://programmercarl.com/%E8%B4%AA%E5%BF%83%E7%AE%97%E6%B3%95%E6%80%BB%E7%BB%93%E7%AF%87.html
- 符号:
- 思路
- 🟢自己的思路和随想录一样
- 🟡自己有思路但随想录思路更好
- 🔴自己毫无思路
- 代码
- 🟩自己写出来且和随想录一样
- 🟨通过但还有其他方法
- 🟥写不出来or没写