当前位置:网站首页>LeetCode179:最大数(C语言)代码简洁!
LeetCode179:最大数(C语言)代码简洁!
2022-08-09 09:29:00 【农场主er】
题目描述
给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。
示例 :
输入: [3,30,34,5,9]
输出: 9534330
说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。
思路分析
首先肯定不能按照整数大小进行排序,比较的规则如下:
- 将整数a、b分别转化为字符串s1、s2;
- 比较
s1+s2和s2+s1(+表示拼接)的大小,根据结果再对a、b进行排序。
C语言代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//设置字符数组最大(默认)长度
#define MAX_BUFFER 512
//设置比较器
//解释:传入参数*a、*b对应的数组下标前者大吗,当返回值为负值时二者交换位置
int cmpfunc(const void * a, const void * b)
{
char s1[MAX_BUFFER];
char s2[MAX_BUFFER];
//发送格式化输出到 s1、s2 所指向的字符串
sprintf(s1, "%d%d", *(int*)a, *(int*)b);
sprintf(s2, "%d%d", *(int*)b, *(int*)a);
return strcmp(s2, s1);
}
char * largestNumber(int* nums, int numsSize) {
//根据比较器排序数组,好处在于排序前后数组元素类型都没有变化
qsort(nums, numsSize, sizeof(int), cmpfunc);
//特殊情况的处理
if (nums[0] == 0) {
return (char *)"0";
}
char *result = (char*)malloc(sizeof(char)*MAX_BUFFER);
char *tem = result;
for (int i = 0; i < numsSize; i++) {
//在流指针之后将整数传递进tem字符串中
sprintf(tem, "%d", nums[i]);
//移动指针位置,相当于拼接
tem += strlen(tem);
}
return result;
}
代码总结
- 很多类库函数如
sprintf、strcat,由于安全性的问题,在VS中编译的时候会出现很出问题…建议测试的时候还是在网页中进行; - 还有运用字符串拼接函数
strcat解题的思路。问题在于控制台运行没有错误,一提交结果就莫名其妙多出来几个数字,如果有心人发现了错误,还请指出。
//只改变了最后几行代码
char result[MAX_BUFFER];
char tem[MAX_BUFFER];
char *a=result;
for (int i = 0; i < numsSize; i++) {
sprintf(tem, "%d", nums[i]);
strcat(result,tem);
}
return a;
复杂度分析
- 时间复杂度:
O(n lg n)。由排序算法决定,qsort采用快速排序; - 空间复杂度:不好描述,主要原因在于创建了很多辅助字符数组。
欢迎评论区交流~
边栏推荐
- m个样本的梯度下降
- Golang Protobuf 处理
- Ontology Development Diary 01-Jena Configuration Environment Variables
- What are the basic concepts of performance testing?What knowledge do you need to master to perform performance testing?
- 【分布式事务】
- 3.List接口与实现类
- 一篇文章让你彻底搞懂关于性能测试常见术语的定义
- Lecture 4 SVN
- BlockingQueue理论普
- 性能测试的基本概念是什么?做好性能测试需要掌握哪些知识?
猜你喜欢

Cisco common basic configuration of common commands

The div simulates the textarea text box, the height of the input text is adaptive, and the word count and limit are implemented

性能测试报告包括哪些内容?模板范文哪里找?看这里

makefile学习-解决目标文件输出路径问题

nacos从下载到安装集群的

游戏测试的概念是什么?测试方法和流程有哪些?

米斗APP逆向分析
选择黑盒测试用例设计方法的综合策略方案总结

Ontology development diary 04 - to try to understand some aspects of protege

.ts 音频文件转换成 .mp3 文件
随机推荐
Ontology Development Diary 01-Jena Configuration Environment Variables
在anaconda环境中配置cuda和cudnn
网络安全入门基础:IP地址
goproxy.io 证书过期
搭建Tigase进行二次开发
恶意软件查杀工具分享
[Personal study summary] CRC verification principle and implementation
选择黑盒测试用例设计方法的综合策略方案总结
批量修改Shapefile属性表的一种方法(使用gdal.jar)
关于SQL的SELECT查询语句的一般格式的描述2021-05-19
WAVE SUMMIT 2022深度学习开发者峰会
全网最全的软件测试基础知识整理(新手入门必学)
接口开发规范及测试工具的使用
Source GBase database, oracle quote "ORA - 01000: beyond the shop open the cursor"
Do you know the principles of test cases and how to write defect reports?
Go-goroutine 的那些事
Tigase插件编写——注册用户批量查询
Another implementation of lateral view explode
字典
RPC服务远程漏洞