1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| class Solution { public int nextGreaterElement(int n) {
char[] chars = String.valueOf(n).toCharArray();
int leftIndex = -1; for (int i = chars.length - 2; i >= 0; i--) { if (chars[i] < chars[i + 1]) { leftIndex = i; break; } }
if (leftIndex == -1) { return -1; }
for (int i = chars.length - 1; i > leftIndex; i--) { if (chars[i] > chars[leftIndex]) { swap(chars, i, leftIndex); break; } }
reverse(chars, leftIndex + 1, chars.length - 1);
int res = 0; for (int i = 0; i < chars.length; i++) { if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && chars[i] > '7')) { return -1; } res = res * 10 + (chars[i] - '0'); } return res; }
private void reverse(char[] chars, int i, int j) { while (i < j) { swap(chars, i++, j--); } }
private void swap(char[] chars, int i, int j) { char tmp = chars[i]; chars[i] = chars[j]; chars[j] = tmp; } }
|
References
556. Next Greater Element III