题目描述:
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) {
string s=to_string(num);
int i=-1, j=-1;
int max_index=s.size()-1;
// 从字符串末尾开始遍历
for(int k=s.size()-2;k>=0;k--)
{ // 如果能找到k使得k小于当前最大值,说明已经找到一对可以交换的数字
if(s[k]<s[max_index])
{
i=k;
j=max_index;
}
// 找到了更大的数字,但是不确定是否有可以交换的另一个数字,所以先更新下标
else if(s[k]>s[max_index]) max_index=k;
}
if(i!=-1) swap(s[i],s[j]);
return stoi(s);
}
};
本文介绍了一种通过交换数字中的两个位来获得最大可能数值的算法。在给定一个非负整数的情况下,该算法将尝试进行一次数字位的交换,以得到最大的数值结果。文章提供了详细的算法实现,包括如何确定可以交换的数字位以及如何执行交换过程。
521

被折叠的 条评论
为什么被折叠?



