0556. Next Greater Element III (M)
Next Greater Element III (M)
题目
Given a positive integer n
, find the smallest integer which has exactly the same digits existing in the integer n
and is greater in value than n
. If no such positive integer exists, return -1
.
Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1
.
Example 1:
Input: n = 12
Output: 21
Example 2:
Input: n = 21
Output: -1
Constraints:
1 <= n <= 2^31 - 1
题意
给定一个数n,用n中所有位上的数字拼出另一个数m,使m恰好是大于n的最小的整数。
思路
可以看做是31. Next Permutation问题的变体,直接把n拆成单位数组成的数字,用next permutation的方法求值,注意溢出处理即可。
代码实现
Java
class Solution {
public int nextGreaterElement(int n) {
int ans = 0;
char[] digits = (n + "").toCharArray();
int p = digits.length - 1;
while (p >= 1 && digits[p] <= digits[p - 1]) {
p--;
}
if (p == 0) return -1;
int q = p - 1;
p = digits.length - 1;
while (digits[p] <= digits[q]) {
p--;
}
swap(digits, p, q);
reverse(digits, q + 1, digits.length - 1);
for (int i = 0; i < digits.length; i++) {
int d = digits[i] - '0';
// 防止溢出
if (ans > Integer.MAX_VALUE / 10 || ans == Integer.MAX_VALUE / 10 && d > 7) {
return -1;
}
ans = ans * 10 + d;
}
return ans;
}
private void swap(char[] A, int i, int j) {
char tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
private void reverse(char[] A, int p, int q) {
while (p < q) {
swap(A, p++, q--);
}
}
}