当前位置:网站首页>Leetcode-556: the next larger element III

Leetcode-556: the next larger element III

2022-07-05 06:09:00 Chrysanthemum headed bat

leetcode-556: Next bigger element III

subject

Topic linking

Give you a positive integer n , Please find the smallest integer that meets the conditions , It consists of rearranging n Each number present in the consists of , And its value is greater than n . If there is no such positive integer , Then return to -1 .

Be careful , The returned integer should be a 32 An integer , If there is an answer that satisfies the meaning of the question , But it's not 32 An integer , Also return to -1 .
Example 1:

 Input :n = 12
 Output :21

Example 2:

 Input :n = 21
 Output :-1

Problem solving

and leetcode-31: Next spread Same idea , Just based on it , Excessive overflow judgment

Method 1 :

class Solution {
    
public:
    // Overflow judgment 
    bool isValidInt(string& s){
    
        string maxS=to_string(INT_MAX);
        if(s.size()<maxS.size()) return true;
        for(int i=0;i<s.size();i++){
    
            if(s[i]>maxS[i]) return false;
            else if(s[i]==maxS[i]) continue;
            else if(s[i]<maxS[i]) return true;
        }
        return true;
    }

    int nextGreaterElement(int n) {
    
        string s=to_string(n);
        int len=s.size();
        int i=len-2,j=len-1;
        while(i>=0&&s[i]>=s[j]){
    
            i--;
            j--;
        }
        if(i<0) return -1;
        int k=len-1;
        while(s[i]>=s[k]){
    
            k--;
        }
        swap(s[i],s[k]);
        sort(s.begin()+i+1,s.end());

        if(!isValidInt(s)) return -1;
        else return stoi(s);
    }
};
原网站

版权声明
本文为[Chrysanthemum headed bat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050546085782.html