Saturday, January 26, 2019

556. Next Greater Element III


96.55 %
class Solution {
    public int nextGreaterElement(int n) {
        char[] chars = String.valueOf(n).toCharArray();
        int i = 0;
        for (i = chars.length - 1; i > 0; i--) {
            if (chars[i] > chars[i - 1]) break;
        }
        int nextLargerDigit = i;
        if (i != 0) {
            for (int j = chars.length - 1; j > i; j--) {
                if (chars[j] > chars[i - 1] && chars[j] < chars[nextLargerDigit]) {
                    nextLargerDigit = j;
                }
            }
            char temp = chars[i - 1];
            chars[i - 1] = chars[nextLargerDigit];
            chars[nextLargerDigit] = temp;
            Arrays.sort(chars, i, chars.length);
        } else {
            return -1;
        }
        long result = Long.valueOf(new String(chars));
        return result > Integer.MAX_VALUE ? -1 : (int) result;
    }
}

No comments:

Post a Comment