快排 或者 sorted
目录
一、题目
二、解答
假设数组有两个数字,[ 10, 100 ],' 10 ' +' 100 ' >' 100 ' + ' 10 ',所有应该是 [ 100, 10] 。
知道这个排序规则的话,我们可以使用快排。
快排:
- 选择基准数字: 从数字列表中选择一个数字作为基准数字。
- 划分数字列表: 将数字列表中所有“小于”基准数字的数字放在基准数字的左边,所有“大于等于”基准数字的数字放在基准数字的右边。
- 递归排序: 递归地对基准数字左右两边的子列表进行排序。
- 连接数字: 将排序后的子列表连接起来,形成最终的结果。
代码:快排 sorted(当然我们也可以使用自定义排序key)
class Solution(object):
def printMinNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
def quick_sort(nums, low, high):
if low < high:
pivot = partition(nums, low, high)
quick_sort(nums, low, pivot - 1)
quick_sort(nums, pivot + 1, high)
def partition(nums, low, high):
pivot = nums[low]
i = low + 1
j = high
while True:
while i <= high and str(nums[i]) + str(pivot) < str(pivot) + str(nums[i]):
i += 1
while j >= low and str(nums[j]) + str(pivot) > str(pivot) + str(nums[j]):
j -= 1
if i > j:
break
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
nums[low], nums[j] = nums[j], nums[low]
return j
nums_str = [str(num) for num in nums]
quick_sort(nums_str, 0, len(nums_str) - 1)
return "".join(nums_str)
代码:
import functools
class Solution(object):
def printMinNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
def sort_key(a, b):
if str(a) + str(b) < str(b) + str(a):
return -1
elif str(a) + str(b) > str(b) + str(a):
return 1
else:
return 0
rnums=sorted(nums,key=functools.cmp_to_key(sort_key)) #解决cmp参数兼容问题
str_nums=""
for i in rnums:
str_nums+=str(i)
return str_nums #转换为字符串