Largest Number —— Leetcode(sort的妙用)

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.

Note: The result may be very large, so you need to return a string instead of an integer.

sort的妙用,但如下代码里为什么comp函数一定要是static的呢?

如果non-static,sort函数是其他class调用Solution的comp方法,即,

a.comp(b, c);
这需要三个参数;但是,sort的源码里并没有new出一个Solution类用于调用comp方法。

而如果声明为static,则只需要两个参数即可调用comp,所以需要声明为static。

stackoverflow上有详细解释:http://stackoverflow.com/questions/26131112/why-here-stdsort-requires-static-compare-function

class Solution {
public:

    //此处为何是static,stackoverflow上有很好的分析
    static bool comp(string str1, string str2) {
        return str1+str2 > str2+str1;
    }
    
    string largestNumber(vector<int>& nums) {
        vector<string> sv;
        
        int i=0;
        while(i<nums.size()) {
            sv.push_back(std::to_string(nums[i++]));
        }
        
        std::sort(sv.begin(), sv.end(), comp);
        
        string sum;
        int j=0;
        while(j<sv.size()) {
            sum += sv[j++];
        }
        
        //针对sum以0开头的特殊处理,分为"0"和 "0002"两种情况
        while(sum[0]=='0' && sum.size()>1) {
            sum.erase(0,1);
        }
        
        return sum;

    }
    
    
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值