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

剑指offer系列——32.把数组排成最小的数

时间:2020-02-14 19:06:57      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:数组排序   min   amp   数组   说明   turn   offer   code   for   

Q:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
T:
把数组排序,排序后从第一个值开始,假如有元素a和元素b,若ab > ba 则 a应该处于b之后;若ab < ba 则a应该处于b之前;若ab = ba 则 a = b;解释说明:比如 “3” 和 "31"比较谁先谁后, “331” > “313”,‘31’应该处于‘3’之前。

    string PrintMinNumber(vector<int> numbers) {
        string result;
        if (numbers.empty())
            return result;
        sort(numbers.begin(), numbers.end(), [](const int &a, const int &b) { return a < b; });
        string temp = to_string(numbers[0]);
        result = temp;
        string temp2;
        for (int i = 1; i < numbers.size(); i++) {
            temp2 = to_string(numbers[i]);
            string a = temp.append(temp2);
            string b = temp2.append(result);
            result = a < b ? a : b;
            temp = result;
        }
        return result;
    }

剑指offer系列——32.把数组排成最小的数

标签:数组排序   min   amp   数组   说明   turn   offer   code   for   

原文地址:https://www.cnblogs.com/xym4869/p/12308177.html

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