首页 > 其他 > 详细

九度 1504:把数组排成最小的数

时间:2014-03-06 23:11:01      阅读:527      评论:0      收藏:0      [点我收藏+]

题目描述:

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

 

思路

1. 最初的想法是比较两个数时, 较短的数末尾补最后一个数, 比如 233, 23 -> 233, 233. 然后判断会变得比较复杂

2. 正好昨晚和室友闲聊, 谈到说到这道题, 才知道末尾补第一个数才是正解. 233, 23 -> 233, 232

3. 剑指 offer 上的解法更是简单粗暴, 直接将两个数拼出来看看就得了. 233, 23 -> 23233, 23323

4. 看完剑指 offer 上的正解, 真想抽自己的脸

 

代码

 

bubuko.com,布布扣
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;

int numbers[200];
string str_num[200];

bool cmp(const string &str1, const string &str2) {
    string _str1 = str1;
    string _str2 = str2;
    _str1.append(str2);
    _str2.append(str1);

    return _str1 < _str2;

}

int main() {
    int n;
    while(scanf("%d", &n) != EOF) {
        for(int i = 0; i < n; i ++)
            scanf("%d", numbers+i);

        for(int i = 0; i < n; i ++) {
            char str[20];
            sprintf(str, "%d", numbers[i]);
            str_num[i] = str;
        }

        sort(str_num, str_num+n, cmp);

        for(int i = 0; i < n; i ++) {
            cout << str_num[i];
        }
        cout << endl;
    }
    return 0;
}
bubuko.com,布布扣

九度 1504:把数组排成最小的数,布布扣,bubuko.com

九度 1504:把数组排成最小的数

原文:http://www.cnblogs.com/xinsheng/p/3585331.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!