Pointing to Offer - Interview Question 33: Arrange the array into the smallest number

Sort the array into the smallest number


Question: Input an array of positive integers, concatenate all the numbers in the array into a number, and print the smallest one of all the numbers that can be concatenated. For example, if the array {3, 32, 321} is input, the smallest number that can be arranged by these three numbers is 321323.

Input: {3, 32, 321}

Output: 321323

Ideas: 1. The main idea is to use recursion to determine whether two numbers m and n are larger than mn or nm after the merger.
2. It should be noted here that if two numbers represented by int type are combined, it is likely to exceed the range that can be represented by int type, so there is still an invisible large number problem here.
3. The best solution to the problem of large numbers is to use a string to solve it, and the digits of the two numbers mn and nm are the same, and it can be solved by a string.
Summary: So the problem becomes a recursive comparison of whether the two numbers are larger before or after merging, and then output the final merged number, which is the smallest number

Ps: There is still one thing to pay attention to here. Before arranging the array, we must first sort the array, so that the small numbers are in the front, so that it is more advantageous to judge mn and nm later. For example: 1 3 5 4 2, then if it is not sorted, only 13542 can be output, and the sorted array is: 1 2 3 4 5, the corresponding output result is 12345, 12345<13542, this is the importance of sorting before merging

/*
题目:把数组排成最小的数
*/

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;

string minMerge(string str1,string str2){
    //这里有可能str1和str2都是int或者long long类型范围内表示不了的数,所以只能一个字符一个字符的比较
    for (int i = 0; i < str1.size(); i++){
        if ((str1[i] - '0') < (str2[i] - '0')){
            return str1;
        }
        else if ((str1[i] - '0') > (str2[i] - '0')){
            return str2;
        }
    }
    return str1;
}

string PrintMinNumber(vector<int> numbers) {
    string str1;
    string str2;
    sort(numbers.begin(), numbers.end());
    if (numbers.size() == 0){
        return str1;
    }
    str1 = to_string(numbers[0]);
    for (int i = 1; i < numbers.size(); i++){
        str2 = to_string(numbers[i]);
        //用str1保存合并后最小的数
        str1 = minMerge(str1 + str2, str2 + str1);
    }
    return str1;
}

int main(){
    int n;
    cin >> n;
    vector<int> numbers;
    int temp;
    for (int i = 0; i < n; i++){
        cin >> temp;
        numbers.push_back(temp);
    }
    cout << PrintMinNumber(numbers);
    system("pause");
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325503016&siteId=291194637