C++ o(N) solution simple to follow


  • 0
    G
    class Solution {
    public:
        int maximumSwap(int num) {
            
            if(num < 10){
                return num;
            }
            
            pair<int,int> toSwap = {0,0};
            int max = INT_MAX;
            int min = INT_MAX;
            vector<int> temp;
            
            while(num){
                temp.push_back(num % 10);
                num /= 10;
            }
            
            max = 0;
            min = 0;
            
            for(int i = 1; i < temp.size(); ++i){
                if(temp[i] < temp[max]){
                    min = i;
                    
                    if(min != max){
                        toSwap.first = min;
                        toSwap.second = max;
                    }
                }
                else if(temp[i] > temp[max]){
                    max = i;
                    min = i;
                }
            }
            
            swap(temp[toSwap.first],temp[toSwap.second]);
            int result = 0;
            
            while(temp.size() > 0){
                result = result*10 + temp.back();
                temp.pop_back();
            }
            
            return result;
        }    
    };
    

Log in to reply
 

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