import java.util.Arrays;
/**
* @author xnl
* @Description:
* @date: 2022/7/3 21:49
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.nextGreaterElement(230241));
}
public int nextGreaterElement(int n) {
// 转换成字符串
char[] chars = Integer.toString(n).toCharArray();
int i = chars.length - 2;
while (i >= 0 && chars[i] >= chars[i + 1]){
i--;
}
if (i < 0){
return -1;
}
int j = chars.length - 1;
// 从后面开始找,找到比i值大的数
while (j >= 0 && chars[i] >= chars[j]){
j--;
}
// 替换两个的位置
swap(chars, i, j);
// 把后面的结果重新排序
Arrays.sort(chars, i + 1, chars.length );
long l = Long.parseLong(new String(chars));
return l > Integer.MAX_VALUE ? -1 : (int)l;
}
private void swap(char[] arr, int i, int j){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
package com.算法专练.力扣.下一个更大元素III;
import java.util.Arrays;
/**
* @author xnl
* @Description:
* @date: 2022/7/3 21:49
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.nextGreaterElement(230241));
}
public int nextGreaterElement(int n) {
// 转换成字符串
char[] chars = Integer.toString(n).toCharArray();
int i = chars.length - 2;
while (i >= 0 && chars[i] >= chars[i + 1]){
i--;
}
if (i < 0){
return -1;
}
int j = chars.length - 1;
// 从后面开始找,找到比i值大的数
while (j >= 0 && chars[i] >= chars[j]){
j--;
}
// 替换两个的位置
swap(chars, i, j);
// 把后面的结果重新排序
Arrays.sort(chars, i + 1, chars.length );
long l = Long.parseLong(new String(chars));
return l > Integer.MAX_VALUE ? -1 : (int)l;
}
private void swap(char[] arr, int i, int j){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
力扣:556. 下一个更大元素 III
最新推荐文章于 2025-11-30 23:49:47 发布
本文介绍了一个Java实现的算法,用于寻找给定正整数的下一个更大的整数,该整数由相同的数字组成并遵循特定规则。若不存在这样的整数或结果超出整数范围,则返回-1。

188

被折叠的 条评论
为什么被折叠?



