Leetcode-670-maximum Swap

Source: Internet
Author: User
Tags bool

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;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.