码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode-738-Monotone Increasing Digits]

时间:2018-01-15 00:26:59      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:red   tput   equal   ges   gpo   span   output   step   bre   

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]

标签:red   tput   equal   ges   gpo   span   output   step   bre   

原文地址:https://www.cnblogs.com/hellowooorld/p/8284645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!