179. 最大数
Difficulty: 中等
给定一组非负整数 nums
,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。
注意:输出结果可能非常大,所以你需要返回一个字符串而不是整数。
示例 1:
输入:nums = [10,2]
输出:"210"
示例 2:
输入:nums = [3,30,34,5,9]
输出:"9534330"
示例 3:
输入:nums = [1]
输出:"1"
示例 4:
输入:nums = [10]
输出:"10"
提示:
1 <= nums.length <= 100
0 <= nums[i] <= 10<sup>9</sup>
Solution
class Solution:
def largestNumber(self, nums: List[int]) -> str:
left, right = 0, len(nums) - 1
self.sort(nums, left, right)
r = "".join([str(i) for i in nums])
return r if int(r) != 0 else '0'
def sort(self, nums, low, high):
if len(nums) <= 1:
return nums
if low < high:
p = self.partition(nums, low, high)
self.sort(nums, low, p-1)
self.sort(nums, p+1, high)
def partition(self, nums, low, high):
if low >= high:
return
i = low - 1
pivot = nums[high]
for j in range(low, high):
if int(str(nums[j]) + str(pivot)) > int(str(pivot) + str(nums[j])):
i += 1
nums[i], nums[j] = nums[j], nums[i]
nums[i+1], nums[high] = nums[high], nums[i+1]
return i + 1