556. Next Greater Element III

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
class Solution {
    public int nextGreaterElement(int n) {
        char[] ch = (n + "").toCharArray();
        int le = ch.length;
        int i = le - 1;
        while(i > 0 && ch[i - 1] >= ch[i]) i--;
        if(i == 0) return -1;
        i--;
        
        int j = le - 1;
        while(j > i && ch[j] <= ch[i]) j--;
        
        swap(ch, i, j);
        reverse(ch, i + 1);
        
        long val = Long.parseLong(new String(ch));
        return (val <= Integer.MAX_VALUE) ? (int) val : -1;
    }
    public void swap(char[] ch, int i, int j) {
        char tmp = ch[i];
        ch[i] = ch[j];
        ch[j] = tmp;
    }
    
    public void reverse(char[] ch, int i) {
        int j = ch.length - 1;
        while(i < j) {
            swap(ch, i, j);
            i++;
            j--;
        }
    }
}

啊这,不就是next permutation吗,小样换了个马甲照样认识你

posted @ 2020-08-14 13:44  Schwifty  阅读(90)  评论(0)    收藏  举报