Sword finger offer -- 32. Arrange the array into the minimum number

Posted by DEVILofDARKNESS on Tue, 10 Dec 2019 21:40:46 +0100

Title Description:

Input a positive integer array, put all the numbers in the array together to form a number, and print the smallest of all the numbers that can be spliced. For example, if the input array {3, 32321}, the minimum number that can be printed out is 321323.

Solution 1:

After converting int to string, arrange and combine all strings to find the smallest combination. But the time complexity is large, which is O(n!)

class Solution {
public:
        vector<string> storage;
    string PrintMinNumber(vector<int> numbers)
    {  
            string res = "";
            if(numbers.size() == 0) return res;
            vector<string> vec;
            for(int i = 0;i < numbers.size();i++)
            {
                    stringstream ss;
                    ss<<numbers[i];
                    string t;
                    ss>>t;
                    vec.push_back(t);
            }
            helper(vec,0);
            string minstr = storage[0];
            for(int i = 1;i < storage.size();i++)
            {
                    if(storage[i] < minstr)
                    {
                            minstr = storage[i];
                    }
            }
            return minstr;
    }  
    void helper(vector<string> vec,int num)
    {  
            if(num == vec.size()-1)
            {
                    string tmp = "";
                    for(int i = 0;i < vec.size();i++)
                    {
                            tmp += vec[i];
                    }
                    storage.push_back(tmp);
            }
            for(int i = num;i < vec.size();i++)
            {
                    string tmp = vec[num];
                    vec[num] = vec[i];
                    vec[i] = tmp;
                    helper(vec,num+1);
                    vec[i] = vec[num];
                    vec[num] = tmp;
            }
    }  
};

Solution 2:

According to the specific rules, the minimum combination is arranged directly, and the time complexity is O (nlogn).

class Solution {
        public:
        static bool cmp(string s1,string s2) 
        {
            return ((s1+s2) < (s2+s1));
        }
        string PrintMinNumber(vector<int> numbers)
        {
                if(numbers.size() == 0) return "";
                vector<string> vec;
                for(int i = 0;i < numbers.size();i++)
                {
                        stringstream ss; 
                        string t;
                        ss<<numbers[i];
                        ss>>t;
                        vec.push_back(t);
                }
                sort(vec.begin(),vec.end(),cmp);
                string res = ""; 
                for(int i = 0;i < vec.size();i++)
                {
                        res += vec[i];
                }
                return res;
        }
};

 

Topics: Programming