leetcode【剑指offer】45、把数组排成最小的数

在这里插入图片描述
思路一:
将数字转换成字符串,然后自定义大小比较机制进行快排
对于str自定义规则:若字符串x+y>y+x,则下x>y

class Solution:
    def minNumber(self, nums: List[int]) -> str:
        
        def fast_sort(l , r):
            if l >= r:
                return
            i, j = l, r
            pivot = strs[i]
            while i < j:
                while strs[j] + pivot >= pivot + strs[j] and i < j:
                     j -= 1
                strs[i]=strs[j]
                while strs[i] + pivot <= pivot + strs[i] and i < j:
                     i += 1
                strs[j]=strs[i]
            strs[i]=pivot
            fast_sort(l, i - 1)
            fast_sort(i + 1, r)
        
        strs = [str(num) for num in nums]
        fast_sort(0, len(strs) - 1)
        return ''.join(strs)

思路2:使用key定义排序规则

class Solution:
    def minNumber(self, nums: List[int]) -> str:
        def sort_rule(x, y):
            return int(x+y)-int(y+x)#x大返回1,y大返回-1
        
        strs = [str(num) for num in nums]
        strs.sort(key = functools.cmp_to_key(sort_rule))
        return ''.join(strs)

猜你喜欢

转载自blog.csdn.net/qq_40707462/article/details/113008934