首页 > 其他 > 详细

LeetCode 179. 最大数

时间:2021-04-12 16:55:28      阅读:25      评论:0      收藏:0      [点我收藏+]

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

LeetCode 179. 最大数

原文:https://www.cnblogs.com/swordspoet/p/14647569.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!