把数组排成最小的数

来源:互联网 发布:java聊天室设计与实现 编辑:程序博客网 时间:2024/05/29 02:41

题目描述:

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

代码实现:

方法一:指针

#include <iostream>#include <string.h>using namespace std;const int g_MaxNumberLength=10;char* g_StrCombine1=new char[g_MaxNumberLength*2+1];char* g_StrCombine2=new char[g_MaxNumberLength*2+1];int compare(const void* strNumber1, const void* strNumber2){strcpy(g_StrCombine1, *(const char**)strNumber1);strcat(g_StrCombine1, *(const char**)strNumber2);strcpy(g_StrCombine2, *(const char**)strNumber2);strcat(g_StrCombine2, *(const char**)strNumber1);return strcmp(g_StrCombine1, g_StrCombine2);}void PrintMinNumber(int *numbers, int length){if(numbers==NULL || length<=0)return;char** strNumbers=(char**)(new int[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(i=0; i<length; i++)cout<<strNumbers[i];cout<<endl;cout<<endl;for(i=0; i<length; i++)delete[] strNumbers[i];delete[] strNumbers;}void main(){int Num;cin>>Num;int *numbers=new int[Num];for(int i=0; i<Num; i++)cin>>numbers[i];PrintMinNumber(numbers, Num);}
方法二:用string流

#include <iostream>#include <string>#include <sstream>#include <algorithm>using namespace std;bool compare(const string& str1, const string &str2){string s1=str1+str2;string s2=str2+str1;return s1<s2;}void ComArrayMin(int *pArray, int num){int i;string *pStrArray=new string[num];for(i=0; i<num; i++){stringstream stream;stream<<pArray[i];stream>>pStrArray[i];}sort(pStrArray, pStrArray+num, compare);for(i=0; i<num; i++)cout<<pStrArray[i];cout<<endl;delete[] pStrArray;}void main(){int Num;cin>>Num;int *pArray=new int[Num];for(int i=0; i<Num; i++)cin>>pArray[i];ComArrayMin(pArray, Num);}

感谢:http://blog.csdn.net/cxllyg/article/details/7659525

0 0
原创粉丝点击