当前位置:网站首页>0179-Largest Number( 最大数)
0179-Largest Number( 最大数)
2022-06-22 11:54:00 【周先森爱吃素】
这个系列算是出于个人兴趣开的一个新坑吧,最近看到同学刷LeetCode算法题,就想写写那些可以一行Python代码写出来的题目,因此本专栏的文章的解题方式效率不做保证,只为追求“一行的浪漫”。
题目

题解
简单解释一下题目,给定一个非负数组nums,将这些数字拼接到一起形成一个大数,由于该数很大,需要以字符串的形式输出。本题难度为Medium。
代码
这道题的题解思路在于,你不可能遍历所有的组合情况然后选出最大的那种,这样一定会TLE的。可以考虑从字符串的角度来理解,就是两个数字字符a和b是拼接成a+b还是b+a更大在Python中可以依靠等长字符串直接比大小得出结果(因此,如果输入x和y,且x+y < y+x那么此时x应该在后面,因此为了契合默认的升序排序,这里输出一个负数即可)。那么只要对整个字符串列表按照这个规则进行降序排序(内部其实是逐个比较的过程),那么排序的结果其实就是最大数构成的顺序,将他们顺次拼接到一起即可。这里需要注意的是,因为输入非负,所以可能是全0,这时候输出会是000这种格式,这里因为一行不便判断,所以用int函数检查后再转为str输出。
class Solution:
def largestNumber(self, nums: List[int]) -> str:
return str(int("".join(sorted(map(str, nums), key = functools.cmp_to_key(lambda x,y: 1 if x+y < y+x else -1)))))
从下面的提交反馈来看,效率不是很高(时间复杂度为 O ( N ∗ l o g ( N ) ) O(N* log(N)) O(N∗log(N)),空间复杂度为 O ( N ) O(N) O(N)),大家也应当考虑高效的方法,部分题目的高效解法可以参考我的仓库源码。

边栏推荐
- Redis - 7. Opérations de transaction
- Share 7 free super clear video resource stations! Both editing and collection are practical enough to cry!
- Struggle, programmer chapter 38 in the old days, when the road turned to the edge of the forest, I suddenly saw
- Redis - 5. Jedis operation redis6
- Oracle用游标分解号码次数
- 本地裸文件包含
- 分享7个免费超清的影视资源站!不管是剪辑还是珍藏都实用到哭!
- 职场杰出人士的20个好习惯
- Heavyweight live | bizdevops: the way to break the technology situation under the tide of digital transformation
- KNN classification of MATLAB (with source code) is used to realize pixel classification (set the proportion of training set by yourself) and print test accuracy
猜你喜欢

Markov chain, hidden Markov model

Machine learning and deep learning - activation function (to be continued)

Redis - 7、事务操作

Share 7 free super clear video resource stations! Both editing and collection are practical enough to cry!

Redis - 7、事務操作

分享7个免费超清的影视资源站!不管是剪辑还是珍藏都实用到哭!

酷开电视adb

Solution to 55e of Niuke challenge

Foreign lead needs energy, interest, research, diligence and is indispensable

在C#开发中使用第三方组件LambdaParser、DynamicExpresso、Z.Expressions,实现动态解析/求值字符串表达式
随机推荐
本地裸文件包含
input输入框只能输入,0-100之间的数组,保留两位小数
Struggle, programmer chapter 38 in the old days, when the road turned to the edge of the forest, I suddenly saw
Word技巧汇总
Struggle, programmer -- Chapter 36 the falling flower man is independent and the tiny swift flies
CAT敏捷团队教练工作坊 (Coaching Agile Teams) | 8月20日开课
More than half of 2022, no new air outlet
oracle处理插入重复记录的技巧
Software architecture design principles
The input input box can only input an array between 0 and 100, with two decimal places reserved
马尔可夫链(Markov Chain),隐马尔可夫模型
Redis - 7. Opérations de transaction
redisTemplate序列化
Differences between SPI and API
Linux安装部署MySQL5.7(企业常用版)超详细
OGG-01431、01003、01151无奈的处理方式
《Go题库·10》channel和锁的对比
Redis - 8、持久化之RDB(Redis DataBase)
Traditional retail is accelerating the evolution and upgrading to new retail, and retail digitalization is imperative
Redis - 5. Jedis operation redis6