556. Next Greater Element III

Description

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

Sort, time O(n), space O(n)

跟"Next Permutation"相同的做法。

class Solution {
    public int nextGreaterElement(int n) {
        char[] digits = Integer.toString(n).toCharArray();
        int len = digits.length;
        // I) Start from the right most digit and 
        // find the first digit that is
        // smaller than the digit next to it.
        int i = len - 1;
        while (i > 0 && digits[i - 1] >= digits[i]) {
            --i;
        }
        // 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 digits[i - 1]
        int nextGreater = len - 1;
        while (nextGreater >= i && digits[nextGreater] <= digits[i - 1]) {
            --nextGreater;
        }
        // III) Swap the above found smallest digit with digits[i - 1]
        swap(digits, i - 1, nextGreater);
        // IV) Sort the digits after (i-1) in ascending order
        Arrays.sort(digits, i, len);
        // don't forget to check overflow
        long res = Long.parseLong(new String(digits));
        return res < Integer.MAX_VALUE ? (int) res : -1;
    }
    
    public void swap(char[] digits, int i, int j) {
        char tmp = digits[i];
        digits[i] = digits[j];
        digits[j] = tmp;
    }
}

你可能感兴趣的:(556. Next Greater Element III)