Open youngyangyang04 opened 3 months ago
这题值得仔细研究!
class Solution {
public int monotoneIncreasingDigits(int n) {
char[] digits = Integer.toString(n).toCharArray();
int index = digits.length;
for (int i = digits.length - 1; i > 0; i--) {
if (digits[i - 1] > digits[i]) {
digits[i - 1]--;
index = i;
}
}
for (int i = index; i < digits.length; i++) {
digits[i] = '9';
}
return Integer.parseInt(new String(digits));
}
}
// 例1: digits = ['3','3','2'], index = 3
i = 2: 满足 3 > 2, digits = ['3','2','2'], index = 2, 即 332 -> 329
i = 1: 满足 3 > 2, digits = ['2','2','2'], index = 1, 即 329 -> 299
// 例2: digits = ['2','3','2'], index = 3
i = 2: 满足 3 > 2, digits = ['2','2','2'], index = 2, 即 232 -> 229
i = 1: 不满足 2 > 2, 继续遍历
如果你不想按字节操作字符串,那么你也许可以看看我的
struct Solution;
impl Solution {
pub fn monotone_increasing_digits(n: i32) -> i32 {
let mut arr = n.to_string().chars().collect::<Vec<char>>();
let mut flag = arr.len();
for i in (1..arr.len()).rev() {
if arr[i] < arr[i-1] {
arr[i-1] = (arr[i-1].to_string().parse::<i32>().unwrap() - 1).to_string().chars().nth(0).unwrap();
flag = i;
}
}
for i in flag..arr.len() {
arr[i] = '9';
}
arr.into_iter().collect::<String>().parse().unwrap()
}
}
https://www.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