Idea: With a stack structure, the num of int is converted to a vector<int> for storage. With the help of a vector<int>, the elements inside the previous vector are sorted by a large to small sort. Compare these two vectors from 0-size () to determine the position of the position change two elements. Exchange them, and finally the elements inside the vector are output in int mode.
T (n) =o (n); S (n) =o (n);
int maximumswap (int num) {if (num<10) return num; Std::stack<int> St; Save the digital std::vector<int> digits in Num temporarily; Save the number std::vector<int> temp in num; Find the element that needs to be exchanged bool needswap=false;
Is it necessary to swap//to take num numbers out and save them to the vector in the order of the high positions in small marks (num/10!=0) {St.push (num%10);
num/=10;
} st.push (num);
Num-and Vector while (!st.empty ()) {Digits.push_back (St.top ());
St.pop ();
} for (auto digit:digits) {///digits elements are copied to temp in temp.push_back (digit);
} bool Issmaller (int num1, int num2); Std::sort (Temp.begin (), Temp.end (), Issmaller); Temp from large to small sort, sort default from small to large size_t i=0;
Find the highest bit element to be exchanged for (; I<temp.size (); ++i) if (Temp[i]!=digits[i]) {needswap=true;
Break
} if (needswap) {int j=0;
For (J=digits.size ()-1; j>=0;--j)//Must start from the low to find the element that needs to be exchanged if (digits[j]==temp[i]) break; Std::sWAP (Digits[i], digits[j]);
Exchange Operation} num=0;
for (int i=0; i<digits.size (); ++i)//Output The value of the interchange after an int num=num*10+digits[i];
return num; } bool Issmaller (int num1, int num2) {return num1 > num2;}