剑指Offer之把数组排成最小的数

假设一个数组number{3,32,321}则这3个数字排成最小数字321323.

首先想到的方法是全排列,排列出所有的情况,找出最小值,因为number[i]>0,所以可以用字符串比较,比如112,与211,strcmp(112,211)==-1;但是只算排列的话就需要O(n!)如果number[i]元素很大则比较更为耗时。

还有一种方法,按照新的规则进行排序,假设a=12,b=21则ab=1221,ba=2112,因此ab>ba。所以a应该排在b的前面。所以剩下的我们就可以进行一次快排,就能得出结果

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <string>
using namespace std;
int length=10;
char * g_string1=new char[length*2+1];
char * g_string2=new char[length*2+1];
int compare(const void * strNumber1,const void *strNumber2)
{
    strcpy(g_string1,*(const char**)strNumber1);
    strcat(g_string1,*(const char**)strNumber2);
    
    strcpy(g_string2,*(const char**)strNumber2);
    strcat(g_string2, *(const char**)strNumber1);
    return strcmp(g_string1, g_string2);
    
}
long int a[1000000];
void PrintMinNumber(long int *a,int m)
{
    char **number=(char**)(new int[length]);
    for(int i=0;i<m;i++)
    {
        number[i]=new char[length];
        sprintf(number[i], "%ld",a[i]);
    }
    qsort(number, m, sizeof(char*), compare);
    for(int i=0;i<m;i++)
        printf("%s",number[i]);
    printf("\n");

}
int main()
{
   // freopen("/Users/sanyinchen/Workspaces/oc/conse/B_ali/B_ali/in.txt","r",stdin);
    int m;
    while(scanf("%d",&m)!=EOF)
    {
        for(int i=0;i<m;i++)
         scanf("%ld",&a[i]);
        PrintMinNumber(a,m);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值