面试题33把数组排成最小的数
思路:简单直观的思路是对数组中的元素进行全排列对全排列后组成的字符串取最小值即可。
//新颖的想法:用排序来解决这个问题,排序的大小的规则,当mn<nm 时认为m<n 用qsort(strnumbers,length,sizeof(char*),compare)
// 谓词函数 bool compare(const void *strNumber1,constvoid *strNumber2);
//注意:当字符串长度相同时可以用strcmp 来比较大小
接口函数: PrintMinNumber(int*a,int length);
Bool compare(const void * strNumber1,const void *strNumber2);
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
//面试题33把数组排成最小的数 思路: 简单直观的思路是对数组中的元素进行全排列 对全排列后组成的字符串取最小值即可。
//新颖的想法:用排序来解决这个问题,排序的大小的规则,当mn<nm 时认为m<n 用qsort(strnumbers,length,sizeof(char*),compare)
// 谓词函数 bool compare(const void *strNumber1,const void *strNumber2);
//注意:当字符串长度相同时可以用strcmp 来比较大小
char result[1000];
char tempResult[1000];
void Permutation(int *a,int length,int beginIndex)
{
if(beginIndex==length)
{
static int count=0;
if(count==0)
{
char temp[11];
for(int i=0;i<length;i++)
{
static int len=0;
sprintf(result+len,"%d",a[i]);
len=len+strlen(itoa(a[i],temp,10));
}
//cout<<result<<endl;
}
else
{
char temp[11];
int len=0;
for(int i=0;i<length;i++)
{
sprintf(tempResult+len,"%d",a[i]);
len=len+strlen(itoa(a[i],temp,10));
}
//cout<<tempResult<<endl;
if(strcmp(result,tempResult)>0)
{
strcpy(result,tempResult);
}
}
count++;
}
for(int index=beginIndex;index<length;index++)
{
int temp=a[index];
a[index]=a[beginIndex];
a[beginIndex]=temp;
Permutation(a,length,beginIndex+1);
temp=a[index];
a[index]=a[beginIndex];
a[beginIndex]=temp;
}
}
//新颖的方法:排序
int compare(const void* strNumber1, const void* strNumber2);
// int型整数用十进制表示最多只有10位
const int g_MaxNumberLength = 10;
char* g_StrCombine1 = new char[g_MaxNumberLength * 2 + 1];
char* g_StrCombine2 = new char[g_MaxNumberLength * 2 + 1];
void PrintMinNumber(int* numbers, int length)
{
if(numbers == NULL || length <= 0)
return;
//char** strNumbers = (char**)(new int[length]);
char ** strNumbers=new char*[length];
for(int i = 0; i < length; ++i)
{
strNumbers[i] = new char[g_MaxNumberLength + 1];
sprintf(strNumbers[i], "%d", numbers[i]);
}
qsort(strNumbers, length, sizeof(char*), compare);
for(int i = 0; i < length; ++i)
printf("%s", strNumbers[i]);
printf("\n");
for(int i = 0; i < length; ++i)
delete[] strNumbers[i];
delete[] strNumbers;
}
// 如果[strNumber1][strNumber2] > [strNumber2][strNumber1], 返回值大于0
// 如果[strNumber1][strNumber2] = [strNumber2][strNumber1], 返回值等于0
// 如果[strNumber1][strNumber2] < [strNumber2][strNumber1], 返回值小于0
int compare(const void* strNumber1, const void* strNumber2)
{
// [strNumber1][strNumber2]
strcpy(g_StrCombine1, *(const char**)strNumber1);
strcat(g_StrCombine1, *(const char**)strNumber2);
// [strNumber2][strNumber1]
strcpy(g_StrCombine2, *(const char**)strNumber2);
strcat(g_StrCombine2, *(const char**)strNumber1);
return strcmp(g_StrCombine1, g_StrCombine2);
}
int main()
{
int a[]={3,32,321};
int length=sizeof(a)/sizeof(a[0]);
Permutation(a, length, 0);
cout<<result<<endl;
cout<<"新颖的方法:"<<endl;
PrintMinNumber(a,length);
return 0;
}