Largest Number
来源:互联网 发布:adb devices 端口 编辑:程序博客网 时间:2024/06/16 21:24
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
解题思路:
(1)将整型数组转换成字符串数组
(2)对字符串数组按照递减的顺序进行希尔排序
(3)将排序后的字符串用strcat()函数拼接起来
char* largestNumber(int* nums, int numsSize) {
//将整型数组转换成字符串数组char** strNums = (char**)malloc(sizeof(int*)*numsSize);for (int i = 0; i < numsSize; i++){ strNums[i] = (char*)malloc(sizeof(char)*10); sprintf(strNums[i],"%d",nums[i]);}//对字符串数组进行希尔排序,按递减的顺序,判断条件与常规的排序有点不同for (int Incre = numsSize/2; Incre > 0; Incre /= 2){ for (int i = Incre; i < numsSize; i++) { int j; char temp[10]; strcpy(temp, strNums[i]); for (j = i; j >= Incre; j -= Incre) { char str1[20] = {'\0'}; char str2[20] = {'\0'}; sprintf(str1, "%s%s",temp,strNums[j-Incre]); sprintf(str2, "%s%s",strNums[j-Incre],temp); if (strcmp(str1,str2) > 0) strcpy(strNums[j],strNums[j-Incre]); else break; } strcpy(strNums[j],temp); }}//判断数组是不是全部为0if (strcmp(strNums[0],"0") == 0) return "0";//将排序后的数组合并成字符串char* res = (char*)malloc(sizeof(char)*numsSize*10);memset(res,'\0',strlen(res));for (int i = 0; i < numsSize; i++) strcat(res,strNums[i]);for (int i = 0; i < numsSize; i++) free(strNums[i]);free(strNums);return res;
}
0 0
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- Largest Number
- IOS数据持久化之一属性列表(或偏好设置)
- BeanCreationException: Error creating bean with name 'conversionService' defined in class path resou
- 互联网协议入门(一)
- Eclipse MyEclipse 复制项目
- Tomcat部署web项目时出现 An internal error occurred during: "Add Deployment".
- Largest Number
- android开发需要掌握的一些常用命令
- 构建变种版本
- ASP解析JOSN
- SmartUpload上传下载
- SpringMVC+Mysql实例详解 .
- 图的大体架构以及主要知识
- iOS-Core-Animation-Advanced-Techniques(七)
- ASP解析UNCODI \0F24324 \0UAF