Problem Link:https://leetcode.com/problems/next-greater-element-iii/submissions/
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-bitinteger exists, you need to return -1.
Example 1:
Input: 12
Output: 21
Example 2:
Input: 21
Output: -1
AC code :
class Solution {
public:
int nextGreaterElement(int n) {
string s=to_string(n);
int len=s.length();
int i,j=0;
for(i=len-1;i>0;i--)
{
if(s[i-1]<s[i])
{
break;
}
}
if(i==0)
{
return -1;
}
j=len-1;
while(s[j]<=s[i-1])
{
j--;
}
swap(s[i-1],s[j]);
sort(s.begin()+i,s.end());
long long res=stoll(s);
if(res>(INT_MAX))//If no such positive 32-bit integer exists, you need to return -1.
{
return -1;
}
else
{
return res;
}
}
};
AC code2:
class Solution {
public:
int nextGreaterElement(int n) {
/*
//solution 1:
string s=to_string(n);
int len=s.length();
int i,j=0;
for(i=len-1;i>0;i--)
{
if(s[i-1]<s[i])
{
break;
}
}
if(i==0)
{
return -1;
}
j=len-1;
while(s[j]<=s[i-1])
{
j--;
}
swap(s[i-1],s[j]);
sort(s.begin()+i,s.end());
long long res=stoll(s);
if(res>(INT_MAX))//If no such positive 32-bit integer exists, you need to return -1.
{
return -1;
}
else
{
return res;
}
*/
//solution 2:
string s=to_string(n);
next_permutation(s.begin(),s.end());
long long res=stoll(s);
if(res>INT_MAX||res<=n)
{
return -1;
}
else
{
return res;
}
}
};