给定一个长度为n的数组nums,数组由一些非负整数组成,现需要将他们进行排列并拼接,每个数不可拆分,使得最后的结果最大,返回值需要是string类型,否则可能会溢出。
数据范围:,
进阶:时间复杂度 ,空间复杂度:
[30,1]
"301"
[2,20,23,4,8]
"8423220"
[2]
"2"
[10]
"10"
输出结果可能非常大,所以你需要返回一个字符串而不是整数。
from functools import cmp_to_key class Solution: def solve(self , nums: List[int]) -> str: # write code here if nums.count(0) == len(nums): return '0' def comp(a,b): ab = int(str(a)+str(b)) ba = int(str(b)+str(a)) if ab < ba: return 1 elif ab == ba: return 0 else: return -1 nums.sort(key = cmp_to_key(comp)) res = ''.join(map(str, nums)) if res == '': return '0' return res
class Solution: def solve(self , nums: List[int]) -> str: # write code here for j in range(len(nums)): for i in range(0,len(nums)-j-1): if int(str(nums[i])+str(nums[i+1]))<int(str(nums[i+1])+str(nums[i])): nums[i],nums[i+1]=nums[i+1],nums[i] v='' for i in nums: if i!=0&nbs***bsp;v!='': v+=str(i) return v if v else '0'
from functools import cmp_to_key class Solution: def solve(self , nums ): # write code here nums = map(str, nums) def cmp(x, y): return 1 if y+x > x+y else -1 res = sorted(nums, key=cmp_to_key(cmp)) return "".join(res if res[0]!='0' else '0')
# # 最大数 # @param nums int整型一维数组 # @return string字符串 # class Solution: def solve(self , nums ): # write code here temp=-1 floor=len(nums)-1 st=list(map(str,nums)) while floor>0: for i in range(floor): if st[i][0]<st[i+1][0]: temp=st[i+1] st[i+1]=st[i] st[i]=temp elif st[i][0]==st[i+1][0] and len(st[i])>len(st[i+1]): temp=st[i+1] st[i+1]=st[i] st[i]=temp elif st[i][0]==st[i+1][0] and len(st[i])==len(st[i+1]) and int(st[i])<int(st[i+1]): temp=st[i+1] st[i+1]=st[i] st[i]=temp floor-=1 set_st=set(st)#全部是0,则返回0 ‘[0,0,0]’--->0 if len(set_st)==1 and '0' in set_st: return '0' return ''.join(st)
class compare(str): def __lt__(x, y): return x+y > y+x class Solution: def solve(self , nums ): # write code here if nums[0]==0: return 0 new_num=sorted(nums,key=compare) new_num=[str(i) for i in new_num] return "".join(new_num)