原题:https://leetcode.com/problems/maximum-swap/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]
题目要求交换两位数使得交换后数最大。要使得数最大,首先就考虑最高位的交换,但最高位可能已经是最大的数,所以问题就转变为:
使能替换的最高位的数替换为一个剩下低位数里面最大的数。
从最高位开始遍历,对于每个当前遍历到的数,再从低位开始遍历剩下的数,找到其中最大的一个。
如果找到的数大于当前高位的数,则将其替换;如果没有比当前高位遍历的数更大的数,则高位继续遍历到其低一位重复以上过程。,
class Solution {
public:
int maximumSwap(int num) {
stringstream ss;
ss << num;
string s = ss.str();
for (int i = 0; i < s.size(); i++) {
int max = 0,pos = 0;
for (int j = s.size(); j > i; j--) {
if (s[j] - '0' > max) {
max = s[j] - '0';
pos = j;
}
}
if (max > s[i] - '0') {
char tmp = s[i];
s[i] = s[pos];
s[pos] = tmp;
stringstream sss(s);
sss >> num;
return num;
}
}
return num;
}
};
111 / 111 test cases passed.
Status: Accepted
Runtime: 3 ms
Submitted: 8 minutes ago