556. Next Greater Element III
作者:互联网
This is the similar problem with "31. Next Permutation", the differences are:
1. 31 don't care about whether the "next" is larger or not, but 556 care, 556 need the next is larger than it.
2. 31's input is an array, while 556 is a number.
3. for 556, If the result is larger than Integer.MAX_VALUE, return -1.
The solution is as following:
public int nextGreaterElement(int n) { char[] cs = (n + "").toCharArray(); //1. convert number to an array! int index = 0; for (int i = cs.length - 1; i > 0; i--) { if (cs[i] > cs[i - 1]) { index = i; break; } } if (index == 0) //2. the next must be larger than the original, for example, 4321's next is 1234, should return -1. 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); long temp = Long.valueOf(new String(cs)); //3. the result might be larger than Integer return temp > Integer.MAX_VALUE ? -1 : (int) temp; } 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 start) { int i = start, j = cs.length - 1; while (i < j) { swap(cs, i, j); i++; j--; } }
标签:index,larger,Greater,temp,int,556,cs,III 来源: https://www.cnblogs.com/feiflytech/p/15861167.html