<p>Given a positive integer <code>n</code>, find <em>the smallest integer which has exactly the same digits existing in the integer</em> <code>n</code> <em>and is greater in value than</em> <code>n</code>. If no such positive integer exists, return <code>-1</code>.</p>

<p><strong>Note</strong> that the returned integer should fit in <strong>32-bit integer</strong>, if there is a valid answer but it does not fit in <strong>32-bit integer</strong>, return <code>-1</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 12
<strong>Output:</strong> 21
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 21
<strong>Output:</strong> -1
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>
</ul>

class Solution {
public:
    int nextGreaterElement(int n) {
        int p=n;
        queue<int>q;
        vector<int> ans;
        while(n!=0){
            int digit=n%10;
            n=n/10;
            ans.push_back(digit);
        }
        reverse(ans.begin(),ans.end());
        int k=ans.size();
        int i=-1;
        for( i=k-1;i>=0;i--){
           if(!q.empty() && ans[i]<ans[q.back()]){
               while(ans[q.front()]<=ans[i]) q.pop();
               swap(ans[i],ans[q.front()]);
               sort(ans.begin()+i+1,ans.end());
               break;
           }
           else q.push(i);
        }
        long long num=0;
        for(int i=0;i<k;i++){
            num=num*10+ans[i];
        }
        if(num>INT_MAX) return -1;
        if(num==p) return-1;
        return num;
    }
};
7600