Description
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: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: 9973
Output: 9973
Explanation: No swap.
Note:
- The given number is in the range [0, 108]
Solution
Greedy
通过找规律可以发现,从前往后遍历digit,如果发现digit i 后面有比它大的元素,则 i 就是要被交换的位置,j 是 i 往后最大的元素的下标(如果最大元素相等则找到最后一个下标),交换 i 和 j 即可。
class Solution {
public int maximumSwap(int num) {
char[] arr = String.valueOf(num).toCharArray();
int n = arr.length;
int[] maxIdx = new int[n];
maxIdx[n - 1] = n - 1;
for (int i = n - 2; i >= 0; --i) {
if (arr[i] <= arr[maxIdx[i + 1]]) {
maxIdx[i] = maxIdx[i + 1];
} else {
maxIdx[i] = i;
}
}
for (int i = 0; i < n - 1; ++i) {
if (arr[i] < arr[maxIdx[i]]) {
swap(arr, i, maxIdx[i]);
break;
}
}
return Integer.parseInt(String.valueOf(arr));
}
public void swap(char[] arr, int i, int j) {
char tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
上面的写法不免繁琐,可以用枚举法来简化。因为十进制数字每一位都在[0, 9]之间,可以用一个大小为10的int[] last保存每个值对应的最大idx。
class Solution {
public int maximumSwap(int num) {
char[] arr = String.valueOf(num).toCharArray();
int n = arr.length;
int[] last = new int[10];
for (int i = 0; i < n; ++i) {
last[arr[i] - '0'] = i;
}
for (int i = 0; i < n; ++i) {
for (int d = 9; d > arr[i] - '0'; --d) {
if (last[d] > i) {
swap(arr, i, last[d]);
// break won't work because of embedded loop, return directly
return Integer.parseInt(String.valueOf(arr));
}
}
}
return num;
}
public void swap(char[] arr, int i, int j) {
char tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}