Problem

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

Example 3:

Input: 123987
Output: 127389

Solution

class Solution {
    public int nextGreaterElement(int n) {
        char[] num = (n+"").toCharArray();
        int i;
        for (i = num.length-1; i > 0; i--) {
            if (num[i-1] < num[i]) break;
        }
        //when all digits are in decreasing order, no greater num
        if (i == 0) return -1; 
        
        //otherwise we get the last increasing digit: num[i-1]
        //and loop to the end finding the smallest greater digit than num[i-1]
        int smallestGreaterIndex = i;
        int lastIncreasing = num[i-1];
        for (int j = i+1; j < num.length; j++) {
            if (num[j] > lastIncreasing && num[j] <= num[smallestGreaterIndex]) {
                smallestGreaterIndex = j;
            }
        }
        //123987 -> lastIncreasing = 3, smallestGreaterIndex = 5
        //swap 3 and 7 -> 127983
        char temp = num[i-1];
        num[i-1] = num[smallestGreaterIndex];
        num[smallestGreaterIndex] = temp;
        
        //reorder 983 to 389 -> 127389
        Arrays.sort(num, i, num.length);
        
        //parse to long to avoid overflow
        long val = Long.parseLong(new String(num));
        return val > Integer.MAX_VALUE ? -1 : (int) val;
    }
}

linspiration
161 声望53 粉丝