[Prove safety Offer- time efficiency face questions 45]: the minimum number of array arranged

Title Description

Enter a positive integer array, the array of all the numbers arranged in a number spliced ​​together, the splice can print out all numbers smallest one. 3,32,321 input array} {e.g., print the minimum number of three numbers can be arranged to 321,323.

Ideas 1

Obtaining all of the elements arranged in an array, and then find the minimum number of returns. Seeking string arrangement may reference plane 38 questions: string arrangement , the time complexity of the algorithm is O (n!).

Ideas 2

According to the following rule array in ascending order: For the two numbers a and b, if a and b is less than b and a splicing ab stitching BA, then placed in front of a b, 9 and 10,109 e.g. <910, so 10 9 should be in front. After the output element can Sort. code show as below:

class Solution {
public:
    
    static bool cmp(int a, int b){
        string ab = to_string(a) + to_string(b);
        string ba = to_string(b) + to_string(a);
        return ab<ba;
    }
    
    string PrintMinNumber(vector<int> numbers) {
        string ans = "";
        if(numbers.empty())
            return ans;
        
        sort(numbers.begin(), numbers.end(), cmp);
        for(int i=0; i<numbers.size(); i++)
            ans += to_string(numbers[i]);
        return ans;
    }
};

Guess you like

Origin www.cnblogs.com/flix/p/12514287.html