码迷,mamicode.com
首页 > 编程语言 > 详细

把数组排成最小的数

时间:2020-03-28 23:53:36      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:solution   desc   函数   nbsp   lam   sort   http   选项   for   

时间限制: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 返回类型,可以不写,由编译器自动推导 
{} 函数体

把数组排成最小的数

标签:solution   desc   函数   nbsp   lam   sort   http   选项   for   

原文地址:https://www.cnblogs.com/whiteBear/p/12589910.html

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