把数组排成最小的数

时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M 

题目描述

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
 
思路:
  先基于字符串的排序,然后再依次拼接起来
class Solution {
public:
    string PrintMinNumber(vector<int> numbers) {
        sort(numbers.begin(),numbers.end(),[](const int&a,const int &b){
            return to_string(a) + to_string(b) < to_string(a)+to_string(b);
        });
        string res;
        for(auto c:numbers)
        {
            res += to_string(c);
        }
        return res;
    }
};

 

采用常规的比较函数,不使用lambda匿名函数

class Solution {
public:
    static bool cmp(int x, int y){
        return to_string(x) + to_string(y) < to_string(y) + to_string(x);
    }
    string PrintMinNumber(vector<int> numbers) {
        sort(numbers.begin(), numbers.end(), cmp);
        string ans = "";
        for(int i = 0; i < numbers.size(); i++)
            ans += to_string(numbers[i]);
        return ans;
    }
};

 可以发现,使用lambda匿名函数的使用空间要小,那肯定的,少写了一个函数空间大小,而不使用lambda匿名函数,在运行时间上会占有优势。

重要的是,对C++11并没有特别多的了解,导致花较长的时间来看C++11.

lambda匿名函数:优点就是可以写内嵌的匿名函数,不必编写独立函数或函数对象,使代码更加的容易理解和精简
Lambda的形式
[capture] (param) opt->ret{body;}; 
[] 为捕获对象,可以是外部变量,指针,引用等 
() 为参数列表 
opt 函数选项,如mutable等 
ret 返回类型,可以不写,由编译器自动推导 
{} 函数体
原文地址:https://www.cnblogs.com/whiteBear/p/12589910.html