lintcode:Largest Number

Given a list of non negative integers, arrange them such that they
form the largest number.
Example
Given [1, 20, 23, 4, 8], the largest formed number is 8423201.
Note
The result may be very large, so you need to return a string instead of an integer.
Challenge
Do it in O(nlogn) time complexity.

对于两个备选数字a和b, 如果str(a) + str(b) > str(b) + str(b), 则a在b之前,否则b在a之前,按照这个原则对原数组从大到小排序即可。

有几个问题:
1.注意全部是0的情况
2.cmp函数要设为static
因为:非静态成员函数是依赖于具体对象的,而std::sort这类函数是全局的,因此无法再sort中调用非静态成员函数。静态成员函数或者全局函数是不依赖于具体对象的, 可以独立访问,无须创建任何对象实例就可以访问。同时静态成员函数不可以调用类的非静态成员。
3.本程序是用stringstream进行数字到字符串的转化的。但在C++11中已经提供了to_string的全局函数,非常方便。

参见:http://www.cplusplus.com/reference/string/to_string/
和我的博客C++11中的string - to_string/stoi

class Solution {
public:
    /**
     *@param num: A list of non negative integers
     *@return: A string
     */
    static bool cmp(int a,int b){
        string ab;
        string ba;
        stringstream ss;
        ss<<a<<b;
        ab=ss.str();
        ss.str("");
        ss<<b<<a;
        ba=ss.str();
        ss.str("");

        return ab>ba;
    } 

    string largestNumber(vector<int> &num) {
        // write your code here

        sort(num.begin(),num.end(),cmp);

        if(num[0]==0){
            return "0";
        }

        stringstream ss;
        for(int i=0;i<num.size();i++){
            ss<<num[i];
        }

        string res=ss.str();
        ss.str("");
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值