剑指offer-面试题45-把数组排成最小的数-规律

/*
题目:
	给定一个int数组,返回数组中各数字排成的最下字符串。
*/

/*
思路:
	比较两个数字之间的先后顺序,谁排在前面更小,从而对数组进行排序,得到结果。
	两个数字先后顺序的比较方法:两个数字连接,比较两种连接方式得到的字符串哪个大。
*/

#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>


using namespace std;


static bool cmp(int a,int b){
    string astr = to_string(a) + to_string(b);

    string bstr = to_string(b) + to_string(a);

    return astr > bstr;

}

string PrintMinNumber(vector<int> numbers) {
   string res = "";
   int length = numbers.size();
   sort(numbers.begin(),numbers.end(),cmp);

   for(int i = length - 1; i >= 0; i--){
        res += to_string(numbers[i]);
   }

   return res;
}

int main(){
    vector<int> a = {3,32,321};
    cout<<PrintMinNumber(a);
}

   

原文地址:https://www.cnblogs.com/buaaZhhx/p/12031285.html