[leetcode-738-Monotone Increasing Digits]

Posted hellowOOOrld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-738-Monotone Increasing Digits]相关的知识,希望对你有一定的参考价值。

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.)

 

Example 1:

Input: N = 10
Output: 9

 

Example 2:

Input: N = 1234
Output: 1234

 

Example 3:

Input: N = 332
Output: 299

 

Note: N is an integer in the range [0, 10^9].

思路:

The idea is to go from the LSB to MSB and find the last digit, where an inversion happens.
There are 2 cases to consider:

case 1:
In 14267 , we see that inversion happens at 4. In this case, then answer is obtained by reducing 4 to 3, and changing all the following digits to 9.
=> 13999

case 2:
1444267, here eventhough the last inversion happens at the last 4 in 1444, if we reduce it to 3, then that itself breaks the rule. So once we find the last digit where inversion happens, if that digit is repeated, then we have to find the last position of that digit. After that it is same as case1, where we reduce it by 1 and set the remaining digits to 9.
=> 1399999

The steps are:

    1. Convert n into num array in reverse order
    2. Find the leftmost position that is inverted and if the inverted character repeats itself, find the leftmost repeated digit.
    3. Fill the digits after inversion as 9
    4. Reduce the digit that caused the inversion by -1
    5. Reverse back the num array and convert to int
int monotoneIncreasingDigits(int N) {
        string n_str = to_string(N);
        
        int marker = n_str.size();
        for(int i = n_str.size()-1; i > 0; i --) {
            if(n_str[i] < n_str[i-1]) {
                marker = i;
                n_str[i-1] = n_str[i-1]-1;
            }
        }
        
        for(int i = marker; i < n_str.size(); i ++) n_str[i] = 9;
        
        return stoi(n_str);
    }

 

参考:

https://leetcode.com/problems/monotone-increasing-digits/discuss/109811

https://leetcode.com/problems/monotone-increasing-digits/solution/

https://leetcode.com/problems/monotone-increasing-digits/discuss/109794






以上是关于[leetcode-738-Monotone Increasing Digits]的主要内容,如果未能解决你的问题,请参考以下文章

*Leetcode 738. Monotone Increasing Digits

12.Python操作关系型数据库

sql 语句中in ,not in

in memory 和 in the memory

IN610/IN610L/IN612替代NRF52832/NRF52840

in的用法归纳总结