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]
思路:Greedy
Intuition
At each digit of the input number in order, if there is a larger digit that occurs later, we know that the best swap must occur with the digit we are currently considering.
Algorithm
We will compute \text{last[d] = i}last[d] = i, the index \text{i}i of the last occurrence of digit \text{d}d (if it exists).
Afterwards, when scanning the number from left to right, if there is a larger digit in the future, we will swap it with the largest such digit; if there are multiple such digits, we will swap it with the one that occurs the latest.
class Solution {
public int maximumSwap(int num) {
char[] A = Integer.toString(num).toCharArray();
int[] last = new int[10];
for (int i = 0; i < A.length; i++) {
last[A[i] - '0'] = i;
}
for (int i = 0; i < A.length; i++) {
for (int d = 9; d > A[i] - '0'; d--) {
if (last[d] > i) {
char tmp = A[i];
A[i] = A[last[d]];
A[last[d]] = tmp;
return Integer.valueOf(new String(A));
}
}
}
return num;
}
}