Leetcode9月2号打卡

105 阅读1分钟

1.leetcode 670题 最大数的交换

很有意思的题目,保存所有数字的最后出现位置,然后从前往后遍历,一旦在目标数字后有最大的数字(从后往前找) 就进行交换

class Solution {
    public int maximumSwap(int num) {
                char[] chars = (num + "").toCharArray();
        int[] last = new int[10];
        for (int i = 0;i < chars.length;i++){
            last[chars[i] - '0'] = i;
        }

        for (int i = 0;i < chars.length;i++){
            for (int j = 9;j > chars[i] - '0';j--){
                if (last[j] > i){
                    char temp = chars[i];
                    chars[i] = chars[last[j]];
                    chars[last[j]] = temp;
                    return Integer.parseInt(String.valueOf(chars));
                }
            }
        }
        return num;
    }
}