把数组排成最小的数

来源:互联网 发布:java酒店需求分析 编辑:程序博客网 时间:2024/05/21 22:56

题目描述:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

思路:寻找给定数组的一种排序序列,使得所有数依次按照字符串的累加方式累加其它所组成的数最小。而得到这种序列的方法是:对于任意两个数a ,b, 如果ab < ba则a排在b前面,否则a排在b后面。比如a=21,b=3由于213<321因此21排在3前面。

证明:
假设a排在b前面,即:(其它数)a(其它数)b(其它数),则:
(其它数)a(其它数)b(其它数)<=(其它数)b(其它数)a(其它数)
因此对于任意的两个数,如果都按照上面那种排序方式进行排列,那么得到的整个序列累加起来一定是最小。

AC代码:

bool cmp(const string &str1, const string &str2) {    string s1 = str1;    string s2 = str2;    s1.append(str2);    s2.append(str1);    return s1 < s2;}class Solution {public:    string PrintMinNumber(vector<int> numbers) {        int n = numbers.size();        string* s = new string[n];        for(int i = 0; i < n; i++) {            char c[12];            itoa(numbers[i], c);            s[i] = c;        }        sort(s, s + n, cmp);        string result = "";        for(int i = 0; i < n; i++) {            result += s[i];        }        delete []s;        return result;    }    void itoa(int num, char* c) {        int index = 0;        if(num < 0) {            c[index] = '-';            index++;            num = -num;        }        int base = 10;        while(num / base != 0) {            base *= 10;        }        while(num != 0) {        base /= 10;        c[index] = num / base + '0';        num %= base;        index++;        }        c[index] = '\0';    }};
0 0