[LeetCode] Next Greater Element III 下一個較大的元素之三


 

Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.

Example 1:

Input: 12
Output: 21

 

Example 2:

Input: 21
Output: -1

 

這道題給了我們一個數字,讓我們對各個位數重新排序,求出剛好比給定數字大的一種排序,如果不存在就返回-1。這道題給的例子的數字都比較簡單,我們來看一個復雜的,比如12443322,這個數字的重排序結果應該為13222344,如果我們仔細觀察的話會發現數字變大的原因是左數第二位的2變成了3,細心的童鞋會更進一步的發現后面的數字由降序變為了升序,這也不難理解,因為我們要求剛好比給定數字大的排序方式。那么我們再觀察下原數字,看看2是怎么確定的,我們發現,如果從后往前看的話,2是第一個小於其右邊位數的數字,因為如果是個純降序排列的數字,做任何改變都不會使數字變大,直接返回-1。知道了找出轉折點的方法,再來看如何確定2和誰交換,這里2並沒有跟4換位,而是跟3換了,那么如何確定的3?其實也是從后往前遍歷,找到第一個大於2的數字交換,然后把轉折點之后的數字按升序排列就是最終的結果了。最后記得為防止越界要轉為長整數型,然后根據結果判斷是否要返回-1即可,參見代碼如下:

 

解法一:

class Solution {
public:
    int nextGreaterElement(int n) {
        string str = to_string(n);
        int len = str.size(), i = len - 1;
        for (; i > 0; --i) {
            if (str[i] > str[i - 1]) break;
        }
        if (i == 0) return -1;
        for (int j = len - 1; j >= i; --j) {
            if (str[j] > str[i - 1]) {
                swap(str[j], str[i - 1]);
                break;
            }
        }
        sort(str.begin() + i, str.end());
        long long res = stoll(str);
        return res > INT_MAX ? -1 : res;
    }
};

 

下面這種解法博主感覺有些耍賴了,用到了STL的內置函數next_permutation,該數字實現的就是這樣一個功能,找下一個全排序,剛好比當前的值大,貼上來權當好玩:

 

解法二:

class Solution {
public:
    int nextGreaterElement(int n) {
        string str = to_string(n);
        next_permutation(str.begin(), str.end());
        long long res = stoll(str);
        return (res > INT_MAX || res <= n) ? -1 : res;
    }
};

 

類似題目:

Next Greater Element II

Next Greater Element I 

 

參考資料:

https://discuss.leetcode.com/topic/85740/c-4-lines-next_permutation

https://discuss.leetcode.com/topic/86049/simple-java-solution-4ms-with-explanation

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM