spring——spring瞭解(轉載)
阿新 • • 發佈:2022-04-17
This is a similiar problem with https://www.cnblogs.com/feiflytech/p/15862432.html
The only differences are:
1. If no larger number can be returned, this problem return -1
2. Need to judge whether the result number is largen then Integer.MAX_VALUE.
class Solution { public int nextGreaterElement(int n) { String s= String.valueOf(n); char[] cs = s.toCharArray(); int last = cs[cs.length-1]; int index = 0; for(int i=cs.length-1;i>0;i--){ if(cs[i]>cs[i-1]){ index = i; break; } } if(index==0)return -1; for(int i=cs.length-1;i>=index;i--){ if(cs[i]>cs[index-1]) { swap(cs, i, index-1); break; } } reverse(cs, index, cs.length-1); s = String.valueOf(cs); long res = Long.valueOf(s);if(res>Integer.MAX_VALUE) return -1; return (int)res; } private void swap(char[] cs, int i, int j){ char temp = cs[i]; cs[i]=cs[j]; cs[j]=temp; } private void reverse(char[] cs, int i, int j){ while(i<j){ swap(cs, i++, j--); } } }