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 }