670. Maximum Swap[Medium]
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.
Example1:
Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example2:
Input: 9973
Output: 9973
Explanation: No swap.
The given number is in the range [0, 10^8]
Solution
给出一个数字,可以选择其中任意两个数交换一次,使得交换完的数是所有交换选择中最大的那个。
显而易见,肯定是把所有数字中最大的那个放在最高位,如果高位已经不能再大,那就次一位,以此类推。
思路就是用一个整数数组把整个数字按位存放,然后从第一位开始向后比较,找出从当前数字往后找比它大的最大值,然后交换。最后再把数组转成string返回即可。
要注意一些比较坑的地方,比如输入1993,如果从1开始往后找到第一个9就返回交换,那就得不到期望的9913的结果。所以判断条件不能是大于,而应该是大于等于,目的是找到处于相对最低位的最大值。
Complexity analysis
O(n²)
Code
class Solution {
public:
int maximumSwap(int num) {
vector<int> result;
while (num) {
result.push_back(num % 10);
num /= 10;
}
bool flag = false;
for (int i = result.size() - 1; i >= 0 && flag == false; i--) {
int index = i;
int max = result[i];
for (int j = i - 1; j >= 0 && flag == false; j--) {
if (max <= result[j]) {
max = result[j];
index = j;
}
}
if (result[i] < result[index]) {
int temp = result[i];
result[i] = result[index];
result[index] = temp;
flag = true;
}
}
int t = 0;
for (int i = result.size() - 1; i >= 0; i--) {
t *= 10;
t += result[i];
}
return t;
}
};