Java实现 LeetCode 556 下一个更大元素 III(数组的翻转)

556. 下一个更大元素 III

给定一个32位正整数 n,你需要找到最小的32位整数,其与 n 中存在的位数完全相同,并且其值大于n。如果不存在这样的32位整数,则返回-1。

示例 1:

输入: 12
输出: 21
示例 2:

输入: 21
输出: -1

class Solution {
   public int nextGreaterElement(int n) {
        LinkedList<Integer> nums = new LinkedList<>();
        int current = n%10;
        while(n > 0 && (nums.isEmpty() || (current = n%10) >= nums.getLast())) {
            nums.addLast(current);
            n = n / 10;
        }
        if (n == 0) {
            return -1;
        }
        n = n / 10;
        for (int i = 0; i <  nums.size(); i ++) {
            if (nums.get(i)> current) {
                int tmp = nums.get(i);
                nums.set(i, current);
                current = tmp;
                break;
            }
        }
        long result = n *10 + current;
        while(!nums.isEmpty()) {
            result = result*10 + nums.pop();
            if (result > Integer.MAX_VALUE) {
                return -1;
            }
        }
        return (int)result;
    }
}
原文地址:https://www.cnblogs.com/a1439775520/p/13075460.html