670. Maximum Swap(Java)

来源:互联网 发布:papi酱上海话 知乎 编辑:程序博客网 时间:2024/04/28 19:39

Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.

Example 1:

Input: 2736Output: 7236Explanation: Swap the number 2 and the number 7.

Example 2:

Input: 9973Output: 9973Explanation: No swap.

Note:
The given number is in the range [0, 10的8次方]

class Solution {    public int maximumSwap(int num) {        char[] digit = Integer.toString(num).toCharArray();        // record the last position of digit 0 ~ 9 in this num.        // index 为每个位上数字的大小,loc[index]为在digit中最后出现index值的位置        int[] loc = new int[10];         for (int i = 0; i < digit.length; i ++) {            loc[digit[i] - '0'] = i;        }        for (int i = 0; i < digit.length; i ++) {            for (int j = 9; j > digit[i] - '0'; j --) {                // loc[j]表示大数所在位数,i表示小数所在位数,只有当大数位数在小数位数的后面时才互换                if (i < loc[j]) {                    char tmp = digit[i];                    digit[i] = digit[loc[j]];                    digit[loc[j]] = tmp;                    return Integer.valueOf(new String(digit));                }            }        }        return num;    }}