556. Next Greater Element III

Posted gopanama

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了556. Next Greater Element III相关的知识,希望对你有一定的参考价值。

跟字典序那道题一样 找出下一个 大于MAX_VALUE或者相同就return-1

 

 1 class Solution {
 2     public int nextGreaterElement(int n) {
 3         if(n == 0) return -1;
 4         String str = "" + n;
 5         char[] arr = str.toCharArray();
 6         int[] arr1 = new int[arr.length];
 7         for(int i = 0; i < arr.length; i++){
 8             arr1[i] = arr[i] - ‘0‘;
 9         }
10         int i;
11         for(i = arr.length - 1; i > 0; i--){
12             if(arr1[i-1] < arr1[i]){
13                 break;
14             }
15         }
16         if(i != 0){
17             swap(arr1, i-1);
18         }else{
19             return -1;
20         }
21         
22         reverse(arr1, i);
23         String res = "";
24         for(i = 0; i < arr1.length; i++){
25             res += arr1[i];
26         }
27         long res1 = Long.parseLong(res);
28         return (res1 > Integer.MAX_VALUE) ? -1 : (int)res1;
29         
30     }
31     
32     public void swap(int[] arr1, int n){
33         for(int i = arr1.length - 1; i > n; i--){
34             if(arr1[i] > arr1[n]){
35                 int temp = arr1[n];
36                 arr1[n] = arr1[i];
37                 arr1[i] = temp;
38                 break;
39             }
40         }
41     }
42     
43     public void reverse(int[] arr1, int i ){
44         int last = arr1.length - 1;
45         while(i < last){
46             int temp = arr1[i];
47             arr1[i] = arr1[last];
48             arr1[last] = temp;
49             i++;
50             last--;
51         }
52     }
53 }

 

以上是关于556. Next Greater Element III的主要内容,如果未能解决你的问题,请参考以下文章

leetcode556—— Next Greater Element III (JAVA)

556. Next Greater Element III

556. Next Greater Element III下一个更大的数字

[LeetCode] 556. Next Greater Element III

LeetCode 556. 下一个更大元素 III(Next Greater Element III)

Leetcode 556. Next Greater Element III