当前位置:网站首页>Daily question-leetcode556-next larger element iii-string-double pointer-next_ permutation

Daily question-leetcode556-next larger element iii-string-double pointer-next_ permutation

2022-07-04 21:24:00 Li Fan, hurry up

Original link
 Insert picture description here

Note:

Look from the back to the front , Find the first smaller number , Then put him in the back Exchange the smallest number larger than him
And then change all the positions behind him reverse Again , Just return to the answer

The code is as follows :

class Solution {
    
public:
    int nextGreaterElement(int n) {
    
        string s = to_string(n);
        int k = s.size() - 1;
        while(k && s[k - 1] >= s[k]) k --;
        if(!k)  return -1;
        int t = k;
        while(t + 1 < s.size() && s[t + 1] > s[k - 1])  t ++;
        swap(s[k - 1], s[t]);
        reverse(s.begin() + k, s.end());
        long long res = stoll(s);
        if(res > INT_MAX)   return -1;
        return res;

    }
};
原网站

版权声明
本文为[Li Fan, hurry up]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042023136701.html