Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9]
, the largest formed number is 9534330
.
两两比较 可以利用sort函数来排序,自定义compare函数,即比较规则
可用vector来代替数组,容易定位
bool compare(int a,int b){ string t1=to_string(a)+to_string(b); string t2=to_string(b)+to_string(a); return t1>t2; } //return to_string(a)+to_string(b)>to_string(b)+to_string(a); class Solution { public: string largestNumber(vector<int> &num) {//use vector to present array if(num.size()<=0) return ""; sort(num.begin(),num.end(),compare); string res; for(int i=0;i<num.size();i++) res+=to_string(num[i]); return res[0]=='0'?"0":res;//only elements valued 0 } };
leetcode_num179_Largest Number
原文地址:http://blog.csdn.net/eliza1130/article/details/44811613