forked from sachuverma/DataStructures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23. Next Greater Element III.cpp
More file actions
48 lines (39 loc) · 980 Bytes
/
23. Next Greater Element III.cpp
File metadata and controls
48 lines (39 loc) · 980 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
Next Greater Element III
========================
Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1.
Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.
Example 1:
Input: n = 12
Output: 21
Example 2:
Input: n = 21
Output: -1
Constraints:
1 <= n <= 231 - 1
*/
class Solution
{
public:
int nextGreaterElement(int n)
{
vector<int> digits;
while (n)
{
int digit = n % 10;
digits.insert(digits.begin(), digit);
n /= 10;
}
if (next_permutation(digits.begin(), digits.end()))
{
long long number = 0;
for (int i = 0; i < digits.size(); ++i)
number = number * 10 + digits[i];
if (number > INT_MAX)
return -1;
return number;
}
else
return -1;
}
};