My first version brute force solution just switch the chars one by one and compare with the max value. The time complaxity is O(n2).

    public int maximumSwap(int num) {
        String maxString = Integer.toString(num);
        char[] cs = maxString.toCharArray();
        for(int i=0;i<cs.length;i++){
            for(int j=i+1;j<cs.length;j++){
                swap(cs, i, j);
                String digits = new String(cs);
                if(digits.compareTo(maxString)>0){
                    maxString = digits;
                }
                swap(cs, i, j);
            }
        }
        return Integer.valueOf(maxString);
    }
    
    private void swap(char[] cs, int i, int j){
        char c = cs[i];
        cs[i]=cs[j];
        cs[j]=c;
    }

We can have a smarter way to switch the chars. We can search from start to end of the string, try to find the smallest index, which has a largest digit which has a larger index then it, then after swap them, the result shall come out.

How can we find a largest digit wich has a larger index then the smallest index?

1. We need to find the smallest index. This can be done from front to back.

2. We need to find the largest digit. We need to sort the digits and check from large to small, which one has a smaller index then 1. We need to store tree information: a. the digit; b. the index; c the order. The bucket order can satisfy the 3 conditions.

We create a bucket of size 10 to store the 10 digits. In the num, we put the digit's index to the bucket.

The time complexity is O(n*10) = O(n):

    public int maximumSwap(int num) {
        char[] cs = Integer.toString(num).toCharArray();
        int[] buckets = new int[10];
        for(int i=0;i<cs.length;i++){
            int digit = cs[i]-'0';
            buckets[digit]=i;
        }
        
        for(int i=0;i<cs.length;i++){
            for(int j=9;j>cs[i]-'0';j--){
                if(buckets[j]>i){
                    swap(cs, i, buckets[j]);
                    return Integer.valueOf(new String(cs));
                }
            }
        }
        return num;
    }
    
    private void swap(char[] cs, int i, int j){
        char c = cs[i];
        cs[i]=cs[j];
        cs[j]=c;
    }

 

posted on 2022-02-07 15:02  阳光明媚的菲越  阅读(27)  评论(0编辑  收藏  举报