leetcode(7)

leetcode(7)

670. Maximum Swap

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:

  1. The given number is in the range [0, 108]

class Solution {
public:
int maximumSwap(int num) {
vector<int> vecnum;
while(num/10)
{
vecnum.push_back(num%10);
num = num / 10;
}
vecnum.push_back(num%10);
int size=vecnum.size();
int res=0;
vector<int>vecmax;
int curmaxpos=0;
for(int i=0;i<size;i++)
{
if(vecnum[i]>vecnum[curmaxpos])
curmaxpos=i;
vecmax.push_back(curmaxpos);
}        //从后往前,记录到当前位置最大数的位置
for(int i=size-1;i>=0;i--)
if(vecnum[vecmax[i]]!=vecnum[i])
{
swap(vecnum[i],vecnum[vecmax[i]]);
break;
}
for(int i=size-1;i>=0;i--)
{
res=res*10+vecnum[i];
}
return res;
}
};




So BadJust So SoGoodCoolPretty Cool (还没人评过分呢!)
Loading...

发表评论

电子邮件地址不会被公开。 必填项已用*标注