把数组排成最小的数
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印拼接所有数字中最小的一个
解法一:暴力解法,由前往后,逐个与后面数字替换,递归地把所有数字全排列,比较每种数字的大小,O(n^2),比较方法可以将所有数字转变成一个int进行比较,但是无法应对极大数字情况,也可以用个char数组把所有数字存储进入,遍历比较大小,因为每个拼接后的数字都是长度相等的
解法二:最前的位置,选取的数字尽量小,确保高位足够小,用快速排序配上比较函数,关键在于比较函数,任意两个数你你n,m组合,nm>mn,m first; nm<mn, n first
累了,优化不起来了
解法一:
void getMinNum(int* pTempNum, int length, char* MinNum, char* CompNum, int currPos)
{
if (currPos >= length)
{
char temp[50];
*CompNum = '\0';
for (int i = 0; i < length;i++)
{
sprintf(temp, "%d", pTempNum[i]);
strcat(CompNum, temp);
}
if (*MinNum == '\0')
strcpy(MinNum, CompNum);
else
{
char* p1 = MinNum;
char* p2 = CompNum;
while (*p1!='\0')
{
if (*p1 == *p2)
{
p1++;
p2++;
}
else if (*p1 < *p2)
return;
else if (*p1 > *p2)
{
strcpy(MinNum, CompNum);
return;
}
}
}
return;
}
getMinNum(pTempNum, length, MinNum, CompNum,currPos + 1);
for (int j = currPos + 1; j < length; j++)
{
int temp = pTempNum[j];
pTempNum[j] = pTempNum[currPos];
pTempNum[currPos] = temp;
getMinNum(pTempNum, length, MinNum, CompNum,currPos + 1);
temp = pTempNum[j];
pTempNum[j] = pTempNum[currPos];
pTempNum[currPos] = temp;
}
}
void PrintMinNumber(const int* numbers, int length)
{ //_BruteForce
if (numbers == nullptr || length <= 0) return;
int* pTempNum = new int[length]();
for (int i = 0; i < length; i++)
pTempNum[i] = numbers[i];
char* MinNum=new char[50]();
char* CompNum = new char[50]();
getMinNum(pTempNum, length, MinNum, CompNum, 0);
printf("%s", MinNum);
return;
}
解法二:
bool compareFunc(int num1,int num2)
{
char ctemp[50];
char cNum1[50];
char cNum2[50];//频繁申请空间也会降低效率,可移到主函数里
sprintf(cNum1, "%d", num1);
sprintf(ctemp, "%d", num1);
sprintf(cNum2, "%d", num2);
strcat(cNum1, cNum2);
strcat(cNum2, ctemp);
int i = 0;
while (true)
{
if (cNum1[i] == '\0')
{
if (num1 < num2)
return true;
else
return false;
}
else if (cNum1[i] < cNum2[i])
return true;
else if (cNum1[i] > cNum2[i])
return false;
else
i++;
}
return false;
}
void PrintMinNumber1(const int* numbers, int length)
{
if (numbers == nullptr || length <= 0) return;
int* pTempNum = new int[length]();
for (int i = 0; i < length; i++)
pTempNum[i] = numbers[i];
std::sort(pTempNum, pTempNum + length, compareFunc);//排序也可自行实现
for (int i = 0; i < length; i++)
printf("%d", pTempNum[i]);
return;
}