数组------将数组元素排成最小数

来源:互联网 发布:淘宝网q币充值软件 编辑:程序博客网 时间:2024/05/21 09:22

题目描述:
给定一个数组,将其中的元素组合成一个最小数.
分析:
1. 可以使用蛮力枚举的方法,将所有的可能性都枚举出来,算法复杂度是O(n!)
2. 可以自己制定规则,对于两个数字m 和 n ,将其拼接成数字 mn 或 nm ,判断它们的大小.若mn < nm 那就定义m < n,反之 n < m 或 n = m ; 通过这种方法将数组中所有的数都排序(升序),然后得到结果。(实现时,可以将数字转换为字符串并进行拼接,然后都过字符串之间的比较而得到结果)

string MinNum(vector<int>& num){    string ret;    if(num.size() < 1)        return ret;    vector<string> str;    IntToStr(num, str);//使用sprintf函数,将int型整数转换为char型    InsertSort(str);//使用插入排序,将字符串排成升序    for(int i  = 0; i < str.size(); i++)//将升序结果作何成为一个最终结果        ret += str[i];    return ret;}void IntToStr(vector<int>& num, vector<string>& str){    char buf[20];    for(int i = 0; i < num.size(); i++){        spintf(buf, "%d", num[i]);        str.push_back(buf);        memset(buf, '\0', 20);    }}void InsertSort(vector<string>& str){    for(int i = 1; i < str.size(); i++){        string s = str[i];        int loc = i;        while(loc > 0 && compare(str[loc - 1], s)){ //使用compare函数比较两个字符串的大小            str[loc] = str[loc - 1];            loc--;        }        str[loc] = s;    }}bool compare(string& m, string& n){ //根据自定义规则判断另个字符串的大小    string mn = m + n;    string nm = n + m;    if(mn > nm)        return true;    else        return false;}
1 0
原创粉丝点击