Leetcode算法學習日誌-738 Monotone Increasing Digits

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

題意分析

給定一個數N,尋找一個小於等於N的數使得這個數的每一位從左到右遞增。

解法分析

本題使用貪心策略,從右向左看,如果遇到s[i-1]>s[i],則將s[i-1],同時將右方的數都變成‘9’,這樣能保證最大,繼續向左遍歷,遇到上述情況有同樣操作。本代碼中從左向右遍歷,遇到上述情況,記錄相應i,再往左查找,直到s[i-1]<s[i]-1,此時將i右邊的位全部置爲9,同時s[i]--。C++代碼如下:

class Solution {
public:
    int monotoneIncreasingDigits(int N) {
        if(N>=0&&N<=9)
            return N;
        string sn=to_string(N);
        int i;
        for(i=0;i<sn.size()-1;i++){
            if(sn[i]>sn[i+1])
                break;   
        }
        if(i==sn.size()-1)
            return N;
        int j;
        for(j=i;j>0;j--){
            if((sn[j]-1)<sn[j-1])
                continue;
            else
                break;
        }
        sn[j]=sn[j]-1;
        int k;
        for(k=j+1;k<sn.size();k++)
            sn[k]='9';
        int res=stoi(sn);
        return res;   
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章