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 n and 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
Solution:
思路:
Ex. 12443322 ->13222344
0.如果是个纯降序排列的数字,做任何改变都不会使数字变大,直接返回-1
1.从后往前,找找/\到的转折点,也就是Ex中的2,如果从后往前看的话,2是第一个小于其右边位数的数字。再来看如何确定2和谁交换,从后往前遍历,找到第一个大于2的数字交换。
2.然后把转折点之后的数字按升序排列就是最终的结果了。
Time Complexity: O(N) Space Complexity: O(N)
Solution Code:
public class Solution {
public int nextGreaterElement(int n) {
char[] number = (n + "").toCharArray();
int i, j;
// I) Start from the right most digit and
// find the first digit that is
// smaller than the digit next to it.
for (i = number.length - 1; i > 0; i--) {
if (number[i - 1] < number[i]) {
break;
}
}
// If no such digit is found, its the edge case 1.
if (i == 0)
return -1;
// II) Find the smallest digit on right side of (i-1)'th
// digit that is greater than number[i-1]
int x = number[i-1], smallest = i;
for (j = i+1; j < number.length; j++) {
if (number[j] > x && number[j] <= number[smallest]) {
smallest = j;
}
}
// III) Swap the above found smallest digit with
// number[i-1]
char temp = number[i-1];
number[i-1] = number[smallest];
number[smallest] = temp;
// IV) Sort the digits after (i-1) in ascending order
Arrays.sort(number, i, number.length);
long val = Long.parseLong(new String(number));
return (val <= Integer.MAX_VALUE) ? (int) val : -1;
}
}
网友评论