剑指 Offer 45. 把数组排成最小的数

剑指 Offer 45. 把数组排成最小的数

Difficulty: 中等

输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。

示例 1:

输入: [10,2]
输出: "102"

示例 2:

输入: [3,30,34,5,9]
输出: "3033459"

提示:

  • 0 < nums.length <= 100

说明:

  • 输出结果可能非常大,所以你需要返回一个字符串而不是整数
  • 拼接起来的数字可能会有前导 0,最后结果不需要去掉前导 0

Solution

class Solution:
    def minNumber(self, nums: List[int]) -> str:
        if not nums:
            return None
        sortedArr = self.qSort(nums)
        strArr = [str(i) for i in sortedArr]
        return "".join(strArr)


    def qSort(self, arr):
        less = []
        more = []
        pivot_list = []

        if len(arr) <= 1:
            return arr
        else:
            pivot = arr[0]
            for item in arr:
                if int(str(item) + str(pivot)) < int(str(pivot) + str(item)):
                    less.append(item)
                elif int(str(item) + str(pivot)) > int(str(pivot) + str(item)):
                    more.append(item)
                else:
                    if int(item) < int(pivot):
                        less.append(item)
                    elif int(item) > int(pivot):
                        more.append(item)
                    else:
                        pivot_list.append(pivot)
        less = self.qSort(less)
        more = self.qSort(more)
        return less + pivot_list + more

原文地址:https://www.cnblogs.com/swordspoet/p/14502792.html