C++ sort 7 lines 3ms


  • 0
    B

    the number contains at most 9 digits, so cost of sort is not a problem

    class Solution {
    public:
        int maximumSwap(int num) {
            string str = to_string(num), copy = str;
            sort(copy.begin(), copy.end(), greater<char>());
            int len = str.length(), i = 0, j = len - 1;
            while(i < j && str[i] == copy[i]) i++;
            while(i < j && str[j] != copy[i]) j--;
            swap(str[i],str[j]);
            return stoi(str);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.