码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_num179_Largest Number

时间:2017-06-30 15:44:10      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:san   class   compare   margin   elements   orm   val   array   vector   

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来取代数组。easy定位

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

标签:san   class   compare   margin   elements   orm   val   array   vector   

原文地址:http://www.cnblogs.com/yxysuanfa/p/7098368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!