# 下一个更大元素III

C++: using next permutation

 int nextGreaterElement(int n) {     auto digits = to_string(n);     next_permutation(begin(digits), end(digits));     auto res = stoll(digits);     return (res > INT_MAX || res <= n) ? -1 : res; }

Java

``` 1 import java.util.Arrays;
2
3 public class Solution {
4     public int nextGreaterElement(int n) {
5         char[] number = (n + "").toCharArray();
6
7         int i, j;
8         // I) Start from the right most digit and
9         // find the first digit that is
10         // smaller than the digit next to it.
11         for (i = number.length-1; i > 0; i--)
12             if (number[i-1] < number[i])
13                 break;
14
15         // If no such digit is found, its the edge case 1.
16         if (i == 0)
17             return -1;
18
19         // II) Find the smallest digit on right side of (i-1)'th
20         // digit that is greater than number[i-1]
21         int x = number[i-1], smallest = i;
22         for (j = i+1; j < number.length; j++)
23             if (number[j] > x && number[j] <= number[smallest])
24                 smallest = j;
25
26         // III) Swap the above found smallest digit with
27         // number[i-1]
28         char temp = number[i-1];
29         number[i-1] = number[smallest];
30         number[smallest] = temp;
31
32         // IV) Sort the digits after (i-1) in ascending order
33         Arrays.sort(number, i, number.length);
34
35         long val = Long.parseLong(new String(number));
36         return (val <= Integer.MAX_VALUE) ? (int) val : -1;
37     }
38 }```

0条评论