556 Next Greater Element III
Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer nand is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.
Example 1:
Input: 12 Output: 21
Example 2:
Input: 21 Output: -1
题目含义:给定一个正32位整数n,您需要找到大于n但最接近与n的32位整数,它与整数n中存在完全相同的数字。如果没有这样的正32位整数存在,则需要返回-1。
1 public int nextGreaterElement(int n) { 2 char[] digs = (n + "").toCharArray(); 3 int one = digs.length - 2;//从后往前找到第一个小于后面一位数字的数字 4 while (one >= 0) { 5 if (digs[one] < digs[one + 1]) break; 6 one--; 7 } 8 9 if (one < 0) return -1;//没有找到,说明当前数字就是最大的,直接返回-1 10 char minNuber = digs[one]; 11 int smallest = one + 1;//找到one后面,比one值大的集合中最小的一位。互换这一位和one位,可以得到最终结果 12 for (int j = one + 1; j < digs.length; j++) { 13 if (digs[j] > minNuber && digs[j] <= digs[smallest]) 14 smallest = j; 15 } 16 17 char temp = digs[smallest]; 18 digs[smallest] = digs[one]; 19 digs[one] = temp; 20 21 Arrays.sort(digs, one + 1, digs.length); //把one后面的所有数位由低到高排列 22 long value = Long.parseLong(new String(digs)); 23 return value <= Integer.MAX_VALUE ? (int) value : -1; 24 }