数据排列,最小排列数
来源:互联网 发布:fifaol3数据库 编辑:程序博客网 时间:2024/05/18 02:40
http://www.cnblogs.com/biyeymyhjob/archive/2012/09/23/2695637.html
题目描述:
输入一个正整数数组,将它们连接起来排成一个数,输出能排出的所有数字中最小的一个。例如输入数组{32, 321},则输出这两个能排成的最小数字32132。请给出解决问题的算法,并证明该算法。
解析:
对数组进行排序,排序规则:当两个数进行比较时,现将他们转坏为char数组,然后用两个char指针挨个字符进行比较,当其中一个为正常字符,而另一个为‘\0’,则后者指针回溯第一个字符,直到找到第一个不相同的字符,字符大者的对应数为大,或者当两者指针对应字符皆为‘\0’时,此时证明两个数字”相等“。具体实现,见下面参考代码:
比较愚钝的方法,对数组全排列一次,记录下最小的那个排列数
参考代码:
#include <iostream>#include <cmath>#include <vector>#include <algorithm>using namespace std;void itoa(int number,char *str){ char ch[100],*p=str; int sign=1,i; if(number<0) { sign=-1; number=-number; } for(i=0;number!=0;number/=10,i++) { ch[i]=number%10 + '0'; } if(sign==-1) *p='-'; i--; for(;i>=0;i--,p++) *p=ch[i]; *p='\0';}bool cmp(const int a, const int b){ char c1[100], c2[100]; itoa(a, c1); itoa(b, c2); for(char *p = c1, *q = c2; *p != '\0' || *q != '\0' ; ) { if(*p == '\0' && *q != '\0') { p = c1; continue; } else if(*q == '\0' && *p != '\0') { q = c2; continue; } if(*p != *q) { return (*p > *q); } p++,q++; } return false;}int count(int a){ int i = 1; while(a/10 != 0) { a /= 10; i++; } return i;}int main(){ vector<int> num; int d = 0; do { cout << "input data: if over input 0" << endl; cin >> d; if(d == 0) break; num.push_back(d); }while(1); sort(num.begin(), num.end(), cmp); long int result = 0; for(vector<int>::iterator iter = num.begin() ; iter != num.end() ; iter++) { result += *iter * pow(10, count(result)); } cout << endl << "the result is :"; cout << result/10 << endl; return 0;}
0 0
- 数据排列,最小排列数
- 最小排列数
- 最小排列数
- 把数组排列成最小的数
- 把数组排列成最小的数
- 排列数
- 排列数
- 排列数
- 数据排列
- [剑指offer]把数组排列成最小的数
- 剑指offer30--将数组排列成最小的数
- 将数组中的元素排列成一个最小的数
- 剑指offer-把数组排列成最小的数
- 面试OR笔试17——最小排列数
- 排列
- 排列
- 排列
- 排列
- fork与缓存
- 通过trait reference来保存 函数、closure 的调用入口
- QT_QAction
- 01距离 解题报告
- windows下安装redis
- 数据排列,最小排列数
- Python编程习惯
- linux学习之软链接和硬链接
- matlab基础 数据拟合
- 安卓端实现拉出式、抽屉式、仿QQ侧滑菜单效果
- 2015年8月总结
- 【七】C++一些新的关键字 -- new、delete、强制类型转换
- 如何修改mysql5.6.24解压缩版(免安装版或zip版)字符编码
- 再议【苹果、橘子】