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, 10^8]
Analysis
因为题目的最大数字只有八位,所以直接暴力枚举出所有交换一次后得到的数字也不会超时,时间复杂度为O(n^3)。
代码:
class Solution {
public:
int toNum(const vector<int> &num) {
int r = 0;
for (int i : num) {
r *= 10;
r += i;
}
return r;
}
int maximumSwap(int num) {
vector<int> digits;
int temp = num;
do {
digits.push_back(temp % 10);
} while ((temp /= 10) != 0);
reverse(digits.begin(), digits.end());
int m = num;
for (int i = 0; i < digits.size(); i++) {
for (int j = i + 1; j < digits.size(); j++) {
swap(digits[i], digits[j]);
m = max(m, toNum(digits));
swap(digits[i], digits[j]);
}
}
return m;
}
};