您的位置:首页 > 其它

n个正整数联接成一排,组成一个最小的多位整数

2017-02-22 07:11 190 查看
题目描述:

设有n个正整数,将它们联接成一排,组成一个最小的多位整数。

程序输入:n个数

程序输出:联接成的多位数

例如:

n=2时,2个整数32,321连接成的最小整数为:32132,

n=4时,4个整数55,31,312, 33 联接成的最小整数为:312313355

[题目要求]

1. 给出伪代码即可,请给出对应的文字说明,并使用上面给出的例子试验你的算法。

2. 给出算法的时间空间复杂度。算法的时间复杂度为O(nlogn),空间复杂度为O(n)。

3. 证明你的算法。(非常重要)使用插入排序的思路证明。

// 两种方法
#define METHOD1

#ifdef METHOD1
#include "ds.h"
using namespace std;
char *itoa(int num,char *str,int radix)
{

char index[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
unsigned unum; /* 中间变量 */
int i = 0, j, k;

/* 确定unum的值 */
if (radix == 10 && num < 0) /* 十进制负数 */
{
unum = (unsigned)-num;
str[i++] = '-';
}
else /* 其他情况 */
{
unum = (unsigned)num;
}

/* 逆序 */
do {
str[i++] = index[unum%(unsigned)radix];
unum /= radix;
}while (unum);

str[i] = '\0';

if (str[0] == '-')
k = 1;
else
k = 0;

for (j = k; j <= (i-1)/2.0 + k; j++)
{
num = str[j];
str[j] = str[i-j-1+k];
str[i-j-1+k] = num;
}

return str;
}
int compare(const void *elem1, const void *elem2)
{
int a1 = *((int*)(elem1));
int a2 = *((int*)(elem2));
char str1[10] = {'\0'};
char str2[10] = {'\0'};
itoa(a1, str1, 10);
itoa(a2, str2, 10);

char *first = (char*)malloc(20);
char *second = (char*)malloc(20);

strcpy(first, str1);
strcat(first, str2);

strcpy(second, str2);
strcat(second, str1);

return strcmp(first, second);

}

int main()
{
int a[4] = {55, 31, 312, 33};
qsort(a, 4, sizeof(int), compare);
for (int i = 0; i < 4; i++)
printf("%d_",a[i]);
printf("\n");
}
#else

#include <vector>
#include <iostream>
#include <sstream>
#include <cmath>
#include <iterator>
#include <algorithm>
#include <string>
using namespace std;
//自定义的排序方法
bool compare_num(long x, long y)
{
static stringstream ss;
ss.clear();
ss<<x<<" "<<y;
string str_x, str_y;
ss>>str_x>>str_y;//这里把两个数转换成string,以便于获取长度,从而计算出需要乘以10的多少次方
return (x * powl(10, str_y.length()) + y) < (y * powl(10, str_x.length()) + x);
}
int main(int argc, char **argv)
{
long x[] = {55, 31, 312,33};
sort(x, x + 4, compare_num);//用自定的排序方法排序
copy(x, x + 4, ostream_iterator<long>(cout));//将数组用迭代方式逐个拷贝到输出流。
//可以用cout<<x[0]<<x[1]<<x[2];来代替上面的方法。
return 0;
}
#endif

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐