剑指offer:把数组排成最小的数

来源:互联网 发布:aape淘宝正品店有哪些 编辑:程序博客网 时间:2024/04/28 12:16

题目描述

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

class Solution {public:    /*    static bool myCmp(string str1, string str2){        string cat1 = str1 + str2;        string cat2 = str2 + str1;        return cat1 < cat2;    }*/    //用函数对象    struct myCmp{        bool operator()(const string &str1, const string &str2)const{            string cat1 = str1 + str2;            string cat2 = str2 + str1;            return cat1 < cat2;        }    };    string PrintMinNumber(vector<int> numbers) {        string res = "";        int len = numbers.size();        if (len == 0){            return res;        }        vector<string> str;        for (int num : numbers){            str.push_back(to_string(num));        }        //注意使用匿名函数对象myCmp()        sort(str.begin(), str.end(),myCmp());        for (string s : str){            res += s;        }        return res;    }};
0 0
原创粉丝点击