题目描述
给定一个32位正整数 n,你需要找到最小的32位整数,其与 n 中存在的位数完全相同,并且其值大于n。如果不存在这样的32位整数,则返回-1。
示例 1:
输入: 12
输出: 21
示例 2:
输入: 21
输出: -1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/next-greater-element-iii
思路
从后往前找到前一个数i小于后一个数i+1的位置,交换i后比i大的最小数,然后给i后的数排序。
class Solution {
public int nextGreaterElement(int n) {
char[] num = ("" + n).toCharArray();
int l = num.length;
Stack<Integer> stack = new Stack<>();
int index = 0;
for(int i = l-1;i >= 0;i--){
while(!stack.isEmpty() && num[stack.peek()] > num[i]){
index = stack.pop();
}
if(index != 0){
swap(num,i,index);
reverse(num,i+1);
break;
}
stack.push(i);
}
if(index == 0) return -1;
try{
return Integer.parseInt(new String(num));
}catch(Exception e){
return -1;
}
}
public void swap(char[] num,int i,int j){
char tem = num[i];
num[i] = num[j];
num[j] = tem;
}
public void reverse(char[] num,int i){
int j = num.length-1;
while(i < j){
swap(num,i++,j--);
}
}
}